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

Commented Issue: 'Newtonsoft.Json 4.5.11' can't be added on a Windows Phone 8 project [24083]

$
0
0
Attempting to resolve dependency 'Newtonsoft.Json (≥ 4.5.11)'.
'Newtonsoft.Json 4.5.11' already installed.
'Microsoft.AspNet.SignalR.Client 1.0.1' already installed.
Could not install package 'Newtonsoft.Json 4.5.11'. You are trying to install this package into a project that targets 'WindowsPhone,Version=v8.0', but the package does not contain any assembly references that are compatible with that framework. For more information, contact the package author.
Comments: ** Comment from web user: netowp **

Update NuGet Package Manager to the last version and restart Visual Studio

http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c


New Post: 4.5.11 to 5.0.3 Breaking Changes?

$
0
0
The release notes against each download.

Note that the JSON schema stuff will tend to change. The JSON schema spec hasn't been finalized and is continually changing.

Commented Issue: Dictionnary Deserialization Bug with TypeNameHandling [23589]

$
0
0
Using TypeNameHandling in Object

Reding need $type in first property in the json object to read the dictionnary

This does not work :

"Positions": {
"Big": {
"$type": "FormEngine.Model.Position,FormEngine.Model"
},
"$type": "System.Collections.Generic.Dictionary`2[[FormEngine.Model.LayoutType, FormEngine.Model],[FormEngine.Model.Position, FormEngine.Model]], mscorlib"

}


========================
This work

"Positions": {
"$type": "System.Collections.Generic.Dictionary`2[[FormEngine.Model.LayoutType, FormEngine.Model],[FormEngine.Model.Position, FormEngine.Model]], mscorlib",
"Big": {
"$type": "FormEngine.Model.Position,FormEngine.Model"
},


}
Comments: ** Comment from web user: airpaulg **

Sorry for bumping this, but isn't this a bit risky since, based on the [RFC-4627 specs](http://www.ietf.org/rfc/rfc4627.txt), a JSON dictionary should not be based on ordering: "An object is an unordered collection of zero or more name/value pairs..."

Anyways, it's not really about the specs, but mostly because I am using a CouchDB implementation that re-orders my key/value pairing when I insert my JSON and this is pretty troublesome. Json.Net is a really awesome tool, but as of now, because my database is re-ordering the elements I can't deserialize my arrays anymore via the $type attribute. I'll most probably figure out a way to re-order the JSON myself before trying to de-serialize.

Commented Issue: Dictionnary Deserialization Bug with TypeNameHandling [23589]

$
0
0
Using TypeNameHandling in Object

Reding need $type in first property in the json object to read the dictionnary

This does not work :

"Positions": {
"Big": {
"$type": "FormEngine.Model.Position,FormEngine.Model"
},
"$type": "System.Collections.Generic.Dictionary`2[[FormEngine.Model.LayoutType, FormEngine.Model],[FormEngine.Model.Position, FormEngine.Model]], mscorlib"

}


========================
This work

"Positions": {
"$type": "System.Collections.Generic.Dictionary`2[[FormEngine.Model.LayoutType, FormEngine.Model],[FormEngine.Model.Position, FormEngine.Model]], mscorlib",
"Big": {
"$type": "FormEngine.Model.Position,FormEngine.Model"
},


}
Comments: ** Comment from web user: airpaulg **

Must $type be first only for JSON arrays? Or it must be first also for any JSON object?

New Post: Json format keyvalues only

$
0
0
Hello How to get the following format using JSON.NET?

{
"123": "CustomerA",
"345":"CustomerB",
"789":"CustomerC"
}

Currently when I Serialize my object I get the data in the following format
[
{
Name: "CustomerA",
ID: "123"
}
{
Name: "CustomerB",
ID: "345"
}
etc etc
]

Created Issue: Issue serializing enums when the enum value is 0. [24204]

$
0
0
This issue occurs in version Newtonsoft.Json.4.5.11 and not in Newtonsoft.Json.4.5.8

1) Create an enum like this -

public enum Status
{
Ok,
Warning,
Error,
}

2) Use it in a class like below -

public class Response
{
public Status Stat { get;set; }
public Description Desc { get; set; }
}

3) Try to serialize Response class when Stat is "Ok" or enum value is 0. On the JSON side, Stat property comes as "undefined". It should have been 0. However, when Stat is "Warning", on the JSON side, the Stat property appears correctly as 1.

Closed Issue: Inconsistent handling of XmlQualifiedName [24190]

$
0
0
Using the latest prerelease version 5.0.3, If I serialize an XmlQualified name like this:

```
var json = JsonConvert.SerializeObject(new XmlQualifiedName("Foo", "urn:foo"));
```

Produces the following JSON:

```
{"Namespace":"urn:foo","Name":"Foo","IsEmpty":false}
```

But taking that exact string and feeding it back through JSON.NET like so:

```
var qname = JsonConvert.DeserializeObject<XmlQualifiedName>(json);
```

Produces an empty object:

```
{}
```

Commented Issue: Issue serializing enums when the enum value is 0. [24204]

$
0
0
This issue occurs in version Newtonsoft.Json.4.5.11 and not in Newtonsoft.Json.4.5.8

1) Create an enum like this -

public enum Status
{
Ok,
Warning,
Error,
}

2) Use it in a class like below -

public class Response
{
public Status Stat { get;set; }
public Description Desc { get; set; }
}

3) Try to serialize Response class when Stat is "Ok" or enum value is 0. On the JSON side, Stat property comes as "undefined". It should have been 0. However, when Stat is "Warning", on the JSON side, the Stat property appears correctly as 1.
Comments: ** Comment from web user: JamesNK **

```
public enum Status
{
Ok,
Warning,
Error
}

public class EnumTestClass
{
public Status Stat { get; set; }
public string Desc { get; set; }
}

[Test]
public void SerializeEnum()
{
EnumTestClass r = new EnumTestClass() { Desc = "Desc!"};

string s = JsonConvert.SerializeObject(r);

Console.WriteLine(s);
// {"Stat":0,"Desc":"Desc!"}
}
```
Works in the latest version.


Closed Issue: Issue serializing enums when the enum value is 0. [24204]

$
0
0
This issue occurs in version Newtonsoft.Json.4.5.11 and not in Newtonsoft.Json.4.5.8

1) Create an enum like this -

public enum Status
{
Ok,
Warning,
Error,
}

2) Use it in a class like below -

public class Response
{
public Status Stat { get;set; }
public Description Desc { get; set; }
}

3) Try to serialize Response class when Stat is "Ok" or enum value is 0. On the JSON side, Stat property comes as "undefined". It should have been 0. However, when Stat is "Warning", on the JSON side, the Stat property appears correctly as 1.

Closed Issue: Add support for ISupportInitialize interface [21269]

$
0
0
So that deserialization calls BeginInit right after constructing the object and before deserializing properties, and EndInit when it's done.
 
This would allow validation for example of the deserialized values.
Comments: Closing as I still don't want this and there is no demand. Also ISupportInitialize isn't in WinRT so won't be available in many versions of Json.NET which I'm trying to get away from.

Released: Json.NET 5.0 Release 4 (Apr 25, 2013)

$
0
0
  • New feature - Added JsonWriter.SetWriteState to support inheritance from JsonWriter implementations
  • Change - Changed .NET 4.5 portable library and WinRT library to use compiled expressions reflection

Created Release: Json.NET 5.0 Release 4 (Apr 25, 2013)

$
0
0
  • New feature - Added JsonWriter.SetWriteState to support inheritance from JsonWriter implementations
  • Change - Changed .NET 4.5 portable library and WinRT library to use compiled expressions reflection

Created Issue: JSON Schema Parser Fails [24208]

$
0
0
The JSON 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.

Created Issue: DefaultValueHandling.IgnoreAndPopulate sets null to the property in deserialization [24209]

$
0
0
I found if the json node is provided with the default value in the json string, when in deserialization, the corresponding property will be set to null. Please refer to the following code,

public class DefaultHandler
{
public int field1;

[DefaultValue("default")]
public string field2;
}

The default value "default" has been set to property 'field2'.

When the json string is "{\"field1\":0,\"field2\":\"default\"}" and the DefaultValueHandling is Ignore or IgnoreAndPopulate, the value of the field2 of the deserialized object will be NULL, but I am expecting the value to be 'default'.

Updated Wiki: Home

$
0
0

Json.NET

Json.NET is a popular high-performance JSON framework for .NET

Features

  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance, faster than .NET's built-in JSON serializers
  • Write indented, easy to read JSON
  • Convert JSON to and from XML
  • Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8.

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

Download Json.NET from CodePlex or install using NuGet

NuGet

Find getting started guides and comprehensive API documentation here.

Donate

Json.NET is a personal open source project. Started in 2006, I have put hundreds of hours adding, refining and tuning Json.NET with the goal to make it not just the best JSON serializer for .NET but the best serializer for any computer language. I need your help to achieve this.

Click here to lend your support to: Json.NET and make a donation at www.pledgie.com !

Feature Comparison

 Json.NETDataContractJsonSerializerJavaScriptSerializer
Supports JSON   
Supports BSON
   
Supports JSON Schema
   
Supports .NET 2.0
   
Supports .NET 3.5
   
Supports .NET 4.0   
Supports .NET 4.5   
Supports Silverlight   
Supports Windows Phone   
Supports Windows 8   
Supports Portable Class Library   
Open Source   
MIT License   
LINQ to JSON   
Thread Safe   
XPath-like JSON query syntax   
Indented JSON support
   
Efficient dictionary serialization   
Nonsensical dictionary serialization   
Deserializes IList, IEnumerable, ICollection, IDictionary properties
   
Serializes circular references
   
Supports serializing objects by reference
   
Deserializes polymorphic properties and collections
   
Serializes and deserializes multidimensional arrays
   
Supports including type names with JSON   
Globally customize serialization process   
Supports excluding null values when serializing
   
Supports SerializationBinder
   
Conditional property serialization
   
Includes line number information in errors
   
Converts XML to JSON and JSON to XML
   
JSON Schema validation
   
JSON Schema generation from .NET types
   
Camel case JSON property names
   
Non-default constructors support
   
Serialization error handling
   
Supports populating an existing object
   
Efficiently serializes byte arrays as base64 text
   
Handles NaN, Infinity, -Infinity and undefined
   
Handles JavaScript constructors   
Serializes .NET 4.0 dynamic objects
   
Serializes ISerializable objects
   
Supports serializing enums to their text name   
JSON recursion limit support
 
  
Attribute property name customization   
Attribute property order customization   
Attribute property required customization   
Supports ISO8601 dates   
Supports JavaScript constructor dates   
Supports Microsoft AJAX dates   
Unquoted property names support   
Raw JSON support   
Supports reading and writing comments   
Supports BigInteger   
Serializes anonymous types   
Deserializes anonymous types   
Deserializes read only collections   
Opt-in mode serialization   
Opt-out mode serialization   
Field (Serializable) mode serialization 
  
Efficiently stream reading and writing JSON   
Single or double quote JSON content   
Supports overriding a type's serialization   
Supports OnDeserialized, OnSerializing, OnSerialized and OnDeserializing attributes   
Supports serializing private properties   
DataMember attribute support   
MetdataType attribute support   
DefaultValue attribute support   
Serializes DataSets and DataTables   
Serailizes Entity Framework   
Serializes nHibernate   
Case-insensitive property deserialization   
Tracing   

Performance Comparison

The source code for this benchmark is included in the Json.NET unit tests.

My Blog

My blog can be found at http://james.newtonking.com where I post news and updates about Json.NET.

My Twitter

My twitter account can be found at @JamesNK


Updated Wiki: Home

$
0
0

Json.NET

Json.NET is a popular high-performance JSON framework for .NET

Features

  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance, faster than .NET's built-in JSON serializers
  • Write indented, easy to read JSON
  • Convert JSON to and from XML
  • Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8.

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

Download Json.NET from CodePlex or install using NuGet

NuGet

Find getting started guides and comprehensive API documentation here.

Donate

Json.NET is a personal open source project. Started in 2006, I have put hundreds of hours adding, refining and tuning Json.NET with the goal to make it not just the best JSON serializer for .NET but the best serializer for any computer language. I need your help to achieve this.

Click here to lend your support to: Json.NET and make a donation at www.pledgie.com !

Feature Comparison

 Json.NETDataContractJsonSerializerJavaScriptSerializer
Supports JSON   
Supports BSON
   
Supports JSON Schema
   
Supports .NET 2.0
   
Supports .NET 3.5
   
Supports .NET 4.0   
Supports .NET 4.5   
Supports Silverlight   
Supports Windows Phone   
Supports Windows 8   
Supports Portable Class Library   
Open Source   
MIT License   
LINQ to JSON   
Thread Safe   
XPath-like JSON query syntax   
Indented JSON support
   
Efficient dictionary serialization   
Nonsensical dictionary serialization   
Deserializes IList, IEnumerable, ICollection, IDictionary properties
   
Serializes circular references
   
Supports serializing objects by reference
   
Deserializes polymorphic properties and collections
   
Serializes and deserializes multidimensional arrays
   
Supports including type names with JSON   
Globally customize serialization process   
Supports excluding null values when serializing
   
Supports SerializationBinder
   
Conditional property serialization
   
Includes line number information in errors
   
Converts XML to JSON and JSON to XML
   
JSON Schema validation
   
JSON Schema generation from .NET types
   
Camel case JSON property names
   
Non-default constructors support
   
Serialization error handling
   
Supports populating an existing object
   
Efficiently serializes byte arrays as base64 text
   
Handles NaN, Infinity, -Infinity and undefined
   
Handles JavaScript constructors   
Serializes .NET 4.0 dynamic objects
   
Serializes ISerializable objects
   
Supports serializing enums to their text name   
JSON recursion limit support
 
  
Attribute property name customization   
Attribute property order customization   
Attribute property required customization   
Supports ISO8601 dates   
Supports JavaScript constructor dates   
Supports Microsoft AJAX dates   
Unquoted property names support   
Raw JSON support   
Supports reading and writing comments   
Supports BigInteger   
Serializes anonymous types   
Deserializes anonymous types   
Deserializes read only collections   
Opt-in mode serialization   
Opt-out mode serialization   
Field (Serializable) mode serialization 
  
Efficiently stream reading and writing JSON   
Single or double quote JSON content   
Supports overriding a type's serialization   
Supports OnDeserialized, OnSerializing, OnSerialized and OnDeserializing attributes   
Supports serializing private properties   
DataMember attribute support   
MetdataType attribute support   
DefaultValue attribute support   
Serializes DataSets and DataTables   
Serailizes Entity Framework   
Serializes nHibernate   
Case-insensitive property deserialization   
Tracing   

Performance Comparison

The source code for this benchmark is included in the Json.NET unit tests.

My Blog

My blog can be found at http://james.newtonking.com where I post news and updates about Json.NET.

My Twitter

My twitter account can be found at @JamesNK

Created 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 now 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.
```

Commented 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: ** Comment from web user: denyss86 **

Here is console application to reproduce this bug:

```
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var dic = new Dictionary<DateTime, string>();

var time1 = DateTime.UtcNow.Date;

dic.Add(time1, "test");

var json = JsonConvert.SerializeObject(dic);

Console.WriteLine(json);

Console.ReadLine();
}
}
}
```

First install the lastest version of Json.NET and execute this code.

Then install the previous version of Json.NET with the following statement:

```
Install-Package -Id "Newtonsoft.Json" -Version "4.5.11"
```

If you compare both versions, you see that they serialize DateTime different way:

```
Version 5.0.4:
{"2013-04-28T00:00:00Z":"test"}

Version 4.5.11
{"04/28/2013 00:00:00":"test"}

```

If a dictionary was serialized with an older version of Json.NET, the new version cannot deserialize it and throws an exception.

Closed Issue: DefaultValueHandling.IgnoreAndPopulate sets null to the property in deserialization [24209]

$
0
0
I found if the json node is provided with the default value in the json string, when in deserialization, the corresponding property will be set to null. Please refer to the following code,

public class DefaultHandler
{
[DefaultValue(-1)]
public int field1;

[DefaultValue("default")]
public string field2;
}

The default value -1 is set to property field1, and default value "default" is set to property 'field2'.

When the json string is {"field1":-1,"field2":"default"} and the DefaultValueHandling is set to 'IgnoreAndPopulate', the value of field1 will be ZERO and the value of the field2 of the deserialized object will be NULL, but I am expecting the value to be -1 and 'default'. I'm wondering whether it's a bug because it's working as I expected when DefaultValueHandling is set to 'Populate'. And I have to use IgnoreAndPopulate to make serialization ignore the field with default value, but populate the default value in deserialization, but currently it causes problem in deserialization as described in the issue.
Comments: Fixed. See github comments.

Closed Issue: Data loss when serializing a large decimal [24183]

$
0
0
Hi,

I am trying to serialize a list of objects, which contains decimals some times. When I serialize it using BSON it usually works. In some cases, in particular when serializing large decimal values, the BSON serializer loses data.

An example:

``` c#
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System;
using System.IO;

namespace NewtonsoftJsonBugReport
{
static class Program
{
class X
{
public X()
{ }

public X(decimal d)
{
this.Data = d;
}

public decimal Data { get; set; }
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
decimal d = 42386543286548654368345865241M;

byte[] output;

Console.WriteLine("Input value {0}", d);

JsonSerializer jsonSerializer = new JsonSerializer();

using (MemoryStream ms = new MemoryStream())
{
using (JsonWriter writer = new BsonWriter(ms))
{
jsonSerializer.Serialize(writer, new X(d));
}

output = ms.ToArray();
}

using (MemoryStream ms = new MemoryStream(output))
{
using (JsonReader reader = new BsonReader(ms))
{
X x = jsonSerializer.Deserialize<X>(reader);

d = x.Data;
}
}

Console.WriteLine("Output value {0}", d);

Console.ReadKey();
}
}
}
```

As you will see, the input is different from the output. This is obviously unwanted, but it also happens silently.

The cause can be found in the BsonBinaryWriter (about line 114)

``` c#
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
```

All numerics, except Int32 and Int64, are converted to Double, which causes the loss of data.

My suggestion would be:
1. To check if the converted data is the same as the input data. Like this, assuming that we are writing a Decimal:

decimal originalValue = (decimal)value.Value;
double d = Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
decimal convertedValue = Convert.ToDecimal(d);

``` c#
if (originalValue != convertedValue)
{
throw new Exception("Cannot convert value to a lossless representative.");
}
```

2. To include Decimal, Float and other types in BsonType so the writer can convert to and from the right type.

Looking forward to your reply.
Comments: I'd rather not throw an error. That could break apps for people who upgrade and don't mind about potential dataloss.
Viewing all 1767 articles
Browse latest View live


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