Quantcast
Channel: Json.NET
Viewing all 1767 articles
Browse latest View live

Closed Issue: GetErrorContext prevents wrapping of exceptions [24149]

$
0
0
Hi,

We have some code that uses JSON.Net to deserialise an Ext.Direct request in an IHttpHandler.
Some of the parameters have their own custom deserialisers that perform validation for the class in question, for a BIC or IBAN say.
These can throw exceptions.

If we wrap an exception during one of these calls JSON.Net's GetErrorContext throws its own exception, due to _currentErrorContext.Error != error, with the message: "Current error context error is different to requested error."

I believe it should be possible to disable this check, and would rather not have to modify the source myself.

Out of interest, what's it for anyway?

Regards,
Westy

Closed Issue: JSON Schema Parser Fails [24208]

$
0
0
The JSON Schema Parser (V5.04) cannot handle this JSON (as run in Linqpad):

```
string data = @"{""payment_methods"":""Amex, Cash, Check, Discover, Mastercard, Visa"",""restaurantmealprice"":"""",""phone"":""(720) 746-9355"",""reviews"":"""",""website"":""http://pl.yext.com/plclick?pid=476af49678&ids=205234&continue=http%3A%2F%2Fbikerjimsdogs.com&target=website"",""hours"":{""dayHours"":[{""interval"":{""start"":""11:00 AM"",""end"":""10:00 PM""},""day"":""MONDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""10:00 PM""},""day"":""TUESDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""10:00 PM""},""day"":""WEDNESDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""10:00 PM""},""day"":""THURSDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""3:00 AM""},""day"":""FRIDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""3:00 AM""},""day"":""SATURDAY""},{""interval"":{""start"":""11:00 AM"",""end"":""10:00 PM""},""day"":""SUNDAY""}]},""offers"":"""",""reviewOverallReviewRating"":""0"",""businessoverview"":""We specialize in gourmet wild game and ethnic sausages and hot dogs. We've been featured on \""No Reservations\"" with Anthony Bourdain and the Food Networks \""The Best Thing I Ever Ate\""."",""sourcevendor"":""54::60"",""breadcrumb"":""payment_methods=205234_yext_whitelabel#54--phone=205234_yext_whitelabel#54--website=205234_yext_whitelabel#54--hours=205234_yext_whitelabel#54--name=205234_yext_whitelabel#54--businessoverview=205234_yext_whitelabel#54"",""id"":""271210628"",""sourcecomposite"":""205234#54::708859187#60"",""customer_message"":"""",""name"":""Biker Jim's Gourmet Dogs"",""reference_id"":"""",""sourceid"":""205234::708859187"",""editorials"":"""",""images"":"""",""reviewTotalUserReviews"":""0""}";

var schema = JsonSchema.Parse(data);

schema.Dump(); // as: { "id": "271210628" }

```
It shows only one node as 'id' and it has no properties.
Comments: It fails because that's not a JSON schema....?

Closed Issue: Exception while deserializing DateTime in version 5 [24215]

$
0
0
We used Json.NET 4 to serialize Dictionary<DateTime, string> and save it to database.

Now we updated NuGet package to the version 5 and the software throws an exception:

```
// from database
var myjson = "{\"03/27/2013 02:51:38\":\"customer note\"}";

JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(myjson);

Throws exception:

Could not convert string '03/27/2013 02:51:38' to dictionary key type 'System.DateTime'. Create a TypeConverter to convert from the string to the key type object. Path '03/27/2013 02:51:38', line 1, position 23.
```
Comments: I have fixed it so that Json.NET will deserialize the old format dates.

Closed Issue: DefaultSerializationBinder.GetTypeNameFromTypeKey() : Check loaded assemblies before calling LoadWithPartialName() [24174]

$
0
0
Greetings and thanks for this fantastic library.

My issue is this:

When I attempt to deserialize an object that was serialized with types from assemblies that were loaded from outside of the GAC and EXE directories, it fails because it cannot find the assembly in either place when calling Assembly.LoadWithPartialName().

If, however, the list of loaded assemblies is checked with AppDomain.CurrentDomain.GetAssemblies() for a matching assemblyname, this assembly can be used without a call to LoadWithPartialName.

I was able to make this change to the source to solve this issue, but perhaps there is a more elegant solution that doesn't involve source modification, or this feature could be added without much impact?
Comments: Done

Created Issue: Deserialization of Regex objects will fail with FormatException, when a StringEnumConverter is used for serialization [24227]

$
0
0
###Brief
Deserialization of Json-serialized Regex objects fails with a FormatException, when a StringEnumConverter has been used during serialization.

Severity:
Medium; the bug causes the deserialization of any Json data to fail fatally, if it contains Regex object data which had been generated by a serializer using a StringEnumConverter. However, writing your own JsonConverter for Regex objects can mitigate the problem.

Json.NET version:
__5.0.4__ (earlier versions are most likely affected as well).

###Full description
Json-serialization and -deserialization of Regex objects work fine, if the serializer does __not__ use a StringEnumConverter. In this case, Regex objects would serialize into Json such as:
```
{ "pattern": "\\s+[a-z]+", "options": 0 }
```

Adding a StringEnumConverter to the serializer will lead to the _Options_ property of Regex objects being serialized as a string -- in this example "None" -- instead of a number (as one would expect).
```
{ "pattern": "\\s+[a-z]+", "options": "None" }
```

But such a serialized Regex object cannot be deserialized again by Json.NET, regardless whether a StringEnumConverter is added to the (de)serializer or not.

###Cause of bug
__RegexConverter__ has a hard-coded Int32 conversion for RegexOptions values in its private ReadJson method, which will throw a FormatException when it tries to convert a value which has been serialized as
string (by using a StringEnumConverter).

###Current workaround
Implementation of a JsonConverter for Regex objects (and thus not relying on RegexConverter).

###Proposed solution
Replace the hard-coded Int32 conversion in the ReadJson method with a string-to-enum conversion as provided by __System.Enum.Parse(EnumType, String, IgnoreCase)__.
(I would further suggest to set the _IgnoreCase_ parameter to true, which should make the deserialization more robust.)

The proposed solution would also work for enums which have the FlagAttribute set (like RegexOptions).
StringEnumConverter already serializes flag enums properly, and System.Enum.Parse would also be sufficient for their deserialization.

Based on MSDN documentation, System.Enum.Parse(...) should also work in Silverlight and Windows Phone.

Created Issue: CanConvert not called with JsonConverterAttribute [24228]

$
0
0
```
private class DataClass
{
[JsonConverter(typeof(CharBoolConverter))]
public bool Data { get; set; }
}

[Fact]
public void ReadJson()
{
string nullJson = @"{'data': null}";
string trueJson = @"{'data': 'Y'}";
string falseJson = @"{'data': 'N'}";
string emptyJson = @"{'data': ''}";
string errorJson = @"{'data': 'herp derp'}";

Assert.True(JsonConvert.DeserializeObject<DataClass>(trueJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(falseJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(emptyJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(nullJson).Data);
Assert.Throws<Exception>(() =>
JsonConvert.DeserializeObject<DataClass>(errorJson));
}
```

When checking test code coverage in visual studio, if I use the JsonConverter attribute in my DataClass, I get zero coverage on the CanConvert method. If I pass it as a converter in DeserializeObject, CanCovert does get coverage. Is it intentional that CanCovert does not get called when using JsonConverterAttribute?

Is CanConvert only used to find a valid converter for a property when the SerializerSettings contains multiple converters?

Created Issue: Cannot convert nullable int to empty.string [24229]

$
0
0
I used version 4.5.11 before upgrading to 5.0.4.
Suddenly I got an error:


```
Make sure the source type is convertible to the destination type.
When casting from a number, the value must be a number less than infinity.
```

What my code doing is:

```
public class MyContractResolver : ContractResolver
{
public MyContractResolver()
{
NullableValueProviderType = typeof(MyNullableValueProvider);
}
}

And in the MyNullableValueProdiver

public object GetValue(object target)
{
if (type is nullable integer and target == null)
return string.Empty;
}

```

The same code will work for nullable DateTime that returns empty string.
Is this a bug?
If not, at least they have to be consistent.

Thanks,
Revin

StackTrace:
```
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Specified cast is not valid.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.JsonWriter.WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, Object value)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, Formatting formatting, JsonSerializerSettings settings)
at Payroll.Mvc.PayrollBaseController.ModelListData[T](ContractResolver contractResolver, PagedArgument argument, IList`1 list) in c:\Code\PayMetrics\Payroll\Mvc\Utility\PayrollBaseController.cs:line 268
at Payroll.Mvc.Areas.Global.Controllers.AusTaxCodeEffectiveController.ListData(PagedArgument argument) in c:\Code\PayMetrics\Payroll\Mvc\Areas\Global\Controllers\AusTaxCodeEffectiveController.cs:line 59
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:

```

New Post: Deserialize the dataset which contain MySqlDateTime will be exception

$
0
0
var ds = GetDs();;
var rst = Serializer.JsonSerialize(ds);

var dsR = Serializer.JsonXDeserialize<DataSet>(rst);

System.ArgumentOutOfRangeException : 指定的参数已超出有效值的范围。
在 Newtonsoft.Json.Converters.DataTableConverter.GetColumnDataType(JsonToken tokenType) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Converters\DataTableConverter.cs: line 139
在 Newtonsoft.Json.Converters.DataTableConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Converters\DataTableConverter.cs: line 105
在 Newtonsoft.Json.Converters.DataSetConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Converters\DataSetConverter.cs: line 81
在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs: line 1378
在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs: line 164
在 Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\JsonSerializer.cs: line 565
在 Newtonsoft.Json.JsonConvert.DeserializeObject(String value, JsonSerializerSettings settings) 位置 c:\Temp\Json\Working\Newtonsoft.Json\Src\Newtonsoft.Json\JsonConvert.cs: line 913
在 HD.Serialization.Serializer.JsonXDeserialize(String jsonString) 位置 Serializer.cs: line 35
在 HD.DataAccessTest.MySqlDataTimeConvertTest.DataSetToJsonTest() 位置 MySqlDataTimeConvertTest.cs: line 25

Closed Issue: Cannot convert nullable int to empty.string [24229]

$
0
0
I used version 4.5.11 before upgrading to 5.0.4.
Suddenly I got an error:


```
Make sure the source type is convertible to the destination type.
When casting from a number, the value must be a number less than infinity.
```

What my code doing is:

```
public class MyContractResolver : ContractResolver
{
public MyContractResolver()
{
NullableValueProviderType = typeof(MyNullableValueProvider);
}
}

And in the MyNullableValueProdiver

public object GetValue(object target)
{
if (type is nullable integer and target == null)
return string.Empty;
}

```

The same code will work for nullable DateTime that returns empty string.
Is this a bug?
If not, at least they have to be consistent.

Thanks,
Revin

StackTrace:
```
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Specified cast is not valid.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.JsonWriter.WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, Object value)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, Formatting formatting, JsonSerializerSettings settings)
at Payroll.Mvc.PayrollBaseController.ModelListData[T](ContractResolver contractResolver, PagedArgument argument, IList`1 list) in c:\Code\PayMetrics\Payroll\Mvc\Utility\PayrollBaseController.cs:line 268
at Payroll.Mvc.Areas.Global.Controllers.AusTaxCodeEffectiveController.ListData(PagedArgument argument) in c:\Code\PayMetrics\Payroll\Mvc\Areas\Global\Controllers\AusTaxCodeEffectiveController.cs:line 59
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:

```
Comments: DateTime? and int? both break for me with that same error.

For performance reasons json.net now relies on the value returned from the IValueProvider being the same type as the property. I would suggest to use a JsonConverter but unfortunately they are skipped if the value is null, and if I change that then a whole lot of applications will break.

I can't think of a good solution.

Closed Issue: CanConvert not called with JsonConverterAttribute [24228]

$
0
0
```
private class DataClass
{
[JsonConverter(typeof(CharBoolConverter))]
public bool Data { get; set; }
}

[Fact]
public void ReadJson()
{
string nullJson = @"{'data': null}";
string trueJson = @"{'data': 'Y'}";
string falseJson = @"{'data': 'N'}";
string emptyJson = @"{'data': ''}";
string errorJson = @"{'data': 'herp derp'}";

Assert.True(JsonConvert.DeserializeObject<DataClass>(trueJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(falseJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(emptyJson).Data);
Assert.False(JsonConvert.DeserializeObject<DataClass>(nullJson).Data);
Assert.Throws<Exception>(() =>
JsonConvert.DeserializeObject<DataClass>(errorJson));
}
```

When checking test code coverage in visual studio, if I use the JsonConverter attribute in my DataClass, I get zero coverage on the CanConvert method. If I pass it as a converter in DeserializeObject, CanCovert does get coverage. Is it intentional that CanCovert does not get called when using JsonConverterAttribute?

Is CanConvert only used to find a valid converter for a property when the SerializerSettings contains multiple converters?
Comments: It is intentional. JsonConverterAttribute is loaded by the CLR when the type is loaded, and an exception thrown in it if CanConvert was false could be thrown from anywhere, on any thread.

Reviewed: Json.NET 5.0 Release 4 (May 03, 2013)

$
0
0
Rated 5 Stars (out of 5) - Great framework for developer! :)

Closed Issue: Deserialization of Regex objects will fail with FormatException, when a StringEnumConverter is used for serialization [24227]

$
0
0
__EDIT: The report originally referred to RegexConverter as the culprit of the bug, which is wrong. Apparently I am too dumb to read the StackTrace of the exception... :(__


###Brief
Deserialization of Json-serialized Regex objects fails with a FormatException, when a StringEnumConverter has been used during serialization.

Severity:
Medium; the bug causes the deserialization of any Json data to fail fatally, if it contains Regex object data which had been generated by a serializer using a StringEnumConverter. However, writing your own JsonConverter for Regex objects can mitigate the problem.

Json.NET version:
__5.0.4__ (earlier versions are most likely affected as well).

###Full description
Json-serialization and -deserialization of Regex objects work fine, if the serializer does __not__ use a StringEnumConverter. In this case, Regex objects would serialize into Json such as:
```
{ "pattern": "\\s+[a-z]+", "options": 0 }
```

Adding a StringEnumConverter to the serializer will lead to the _Options_ property of Regex objects being serialized as a string -- in this example "None" -- instead of a number (as one would expect).
```
{ "pattern": "\\s+[a-z]+", "options": "None" }
```

But such a serialized Regex object cannot be deserialized again by Json.NET, regardless whether a StringEnumConverter is added to the (de)serializer or not.

###Cause of bug
(EDITED) The exception is thrown by the Int32 conversion of JsonFormatterConverter. The deserialization involving JsonFormatterConverter depends on .NET's Runtime.Serialization process. And somewhere during that process it is decided that the serialized data of property RegexOptions is Int32. I am not sure, whether Json.NET has a say in this, or whether this is handled entirely by .NET's serialization implementation.

###Possible workaround
Implementation of a JsonConverter for Regex objects (and thus not relying on RegexConverter).
Comments: I've made RegexConverter the default way to serialize/deserialize regexes.

Closed Issue: Iso Durations are not serialized/desrialized properly [23602]

$
0
0
Given the following snippet,

var settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat };
settings.Converters.Add(new IsoDateTimeConverter());

var duration = new TimeSpan(0, 1, 0);
Debug.WriteLine(JsonConvert.SerializeObject(duration, settings));

Outputs: "00:01:00"
Should output: "PT1M"

Debug.WriteLine(JsonConvert.DeserializeObject("{\"Duration\": \"PT1M\"}", settings));

Fails: Error converting value "PT1M" to type 'System.TimeSpan'. Path 'Duration', line 1, position 19.
Comments: Create a JsonConverter that serializes TimeSpans to the format you want.

Closed Issue: It's impossible to create custom ReferenceResolver. [24125]

$
0
0
I try to solve problem about JSON referencing like the following code.

```
var json = {};
json.a = { foo: 'bar' };
json.b = { foo: null, parent: json.a };
```

Normally, we can change "ReferenceResolver" setting to proper class to handle reference value.

![Image](http://json.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=json&WorkItemId=24125&FileAttachmentId=6320)

However, JSON.net pass context object as internal class that I cannot access any property on it. Moreover, this internal doesn't has any information about current processing object.

![Image](http://json.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=json&WorkItemId=24125&FileAttachmentId=6319)

So, it's impossible to serialize the above JSON like this.

```
{
"a": { "foo": "bar" },
"b": { "foo": null, parent: "#a" }
}
```

For more information about JSON referencing, please click at the following link.
http://www.sitepen.com/blog/2008/06/17/json-referencing-in-dojo/
Comments: ReferenceResolver example: https://github.com/JamesNK/Newtonsoft.Json/blob/3aff43054fc8efcf85321394e921824fe5ac4094/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs#L8716-L8751

Closed Issue: parsing additional special properties (other than $id, $ref, $type, &value and $values) [21856]

$
0
0
Get or sets the additional special properties (cfr $id, $ref, $type, &value and $values) and it handling functions.
ex: A json can contain a special deferred property:
"Patient": {
"$deferred": "http://server/patients/457892/",
}
so you can create something like oData Deferred Content http://www.odata.org/developers/protocols/json-format#DeferredContent

SpecialPropertiesReadHandling.Add("$deferred", (reader, objectType, contract, member, existingValue, target, reference, serializer) =>
{
reader.Read();
string value = (reader.Value != null) ? reader.Value.ToString() : null;

Debug.WriteLine(value); //in our example will print "http://server/patients/457892/"
//here we can do some cool stuff like creating a dynamic proxy that will handle the deferred loading

reader.Read();
return null;
});

setting the "$deferred" property can be done by a custom converter
Comments: I don't want to add this. You might be able to get something similar from combining ExtensionData (new feature just added) with an on deserialized event.

Closed Issue: NewtonSoft.Json.Linq Namespace Entities not marked as [Serializable]? [21595]

$
0
0
I've got a caching mechanism that's using the DataContractSerializer as a best-effort serializer for anything the cache receives. The problem is the JObject (and it's children) aren't marked as [Serializable] and cannot be serialized by this method.
 
I know the library is a serialization framework in itself, but It's a bit upsetting that it doesn't play nice with other serializers.
 
Here's the stack trace into the serializer when a JObject is attempted to be serialized:
 
System.Runtime.Serialization.InvalidDataContractException: Type 'Newtonsoft.Json.Linq.JObject' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
at System.Runtime.Serialization.CollectionDataContract.GetValidContract(SerializationMode mode)
at System.Runtime.Serialization.NetDataContractSerializer.GetDataContract(RuntimeTypeHandle typeHandle, Type type, Hashtable& surrogateDataContracts)
at System.Runtime.Serialization.NetDataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(Stream stream, Object graph)
 
Marking the object with [Serializable] and potentially ISerializable (to hook the proper serialization methods in the library) should allow it to be serialized properly.
Comments: Sorry, I still don't want to do this. I'm trying to limit what is added to json.net so the dll doesn't grow too big.

Commented Issue: It's impossible to create custom ReferenceResolver. [24125]

$
0
0
I try to solve problem about JSON referencing like the following code.

```
var json = {};
json.a = { foo: 'bar' };
json.b = { foo: null, parent: json.a };
```

Normally, we can change "ReferenceResolver" setting to proper class to handle reference value.

![Image](http://json.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=json&WorkItemId=24125&FileAttachmentId=6320)

However, JSON.net pass context object as internal class that I cannot access any property on it. Moreover, this internal doesn't has any information about current processing object.

![Image](http://json.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=json&WorkItemId=24125&FileAttachmentId=6319)

So, it's impossible to serialize the above JSON like this.

```
{
"a": { "foo": "bar" },
"b": { "foo": null, parent: "#a" }
}
```

For more information about JSON referencing, please click at the following link.
http://www.sitepen.com/blog/2008/06/17/json-referencing-in-dojo/
Comments: ** Comment from web user: SoulMaster **

It is a limitation of deserialization process that cannot access JToken object or structure of current serialized object. So, we need to keep data in "$id" property and add in dictionary to search later.

However, I still prefer path-based reference because it generates very small without provide any information in "$id" property.

```
var json =
[
{
"Name": "John Smith",
"Spouse":
{
"Name": "Jane Smith",
"Spouse": { "$ref": "[0]" }
}
},
{
"$ref": "[0].Spouse"
}
]
```

Patch Uploaded: #14443

$
0
0

dejarp has uploaded a patch.

Description:
Trying to resolve contract for an unbound generic type throws exception "Invalid type owner for DynamicMethod". I'm not sure whether GenericTypeDefinitions are intentionally excluded here or whether this is actually a bug.

New Post: Method not found 'Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)

$
0
0
JeanPaulSmit wrote:
I'm having the same issue, it seems to be related to the Visual Studio version you're using and the version of the MVC 4 package (beta/RC). Unfortunately I haven't fixed it.
Is there any workaround for it?

Released: Json.NET 5.0 Release 5 (May 08, 2013)

$
0
0
  • New feature - Added global default serialization settings with JsonConvert.DefaultSettings
  • New feature - Added extension data support with JsonExtensionDataAttribute
  • New feature - Added NullValueHandling and DefaultValueHandling support to serializing dynamic types
  • Change - Changed some explicit interface methods on JArray to public to support use with ImpromtuInterface
  • Fix - Fixed deserializing non-ISO formatted date dictionary keys
  • Fix - Fixed values not being set when deserializing with DefaultValueHandling.IgnoreAndPopulate
  • Fix - Fixed deserializing with type named handling and assemblies loaded with Assembly.LoadFrom
  • Fix - Fixed deserializing Regexes when using StringEnumConverter
  • Fix - Fixed serializing and deserializing typed DataSets
Viewing all 1767 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>