Json.NET 4.5 Release 10 – Portable Class Library on NuGet

Json.NET's major new feature this release is the portable class library assembly is available over NuGet. This is made possible by NuGet 2.1 supporting portable class libraries. Read more about NuGet 2.1 here.

Case insensitive JObject GetValue and TryGetValue

To simplify getting property values without worrying about the property name's case a couple of helper methods have been added to JObject. GetValue and TryGetValue will first attempt to get a property value with the exact case after which it will ignore case and the first matching property will be returned.

JObject o = JObject.Parse(@"{
  'name': 'Lower',
  'NAME': 'Upper'
}");
 
string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase);
// Upper
 
string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase);
// Lower

In this example the first call to GetValue with "NAME" exactly matches the second property. The second call to GetValue with "Name" doesn’t exactly match any of the properties so a case insensitive search is made and the first property is returned.

Changes

Here is a complete list of what has changed since Json.NET 4.5 Release 9.

  • New feature - Added Portable build to NuGet package
  • New feature - Added GetValue and TryGetValue with StringComparison to JObject
  • Change - Improved duplicate object reference id error message
  • Fix - Fixed error when comparing empty JObjects
  • Fix - Fixed SecAnnotate warnings
  • Fix - Fixed error when comparing DateTime JValue with a DateTimeOffset JValue
  • Fix - Fixed serializer sometimes not using DateParseHandling setting
  • Fix - Fixed error in JsonWriter.WriteToken when writing a DateTimeOffset
  • Fix - Fixed error when serializing emitted classes that have null constructor parameter names
  • Fix - Fixed empty strings not correctly deserializing as null onto nullable properties

Links

Json.NET CodePlex Project

Json.NET 4.5 Release 10 Download – Json.NET source code and assemblies

Json.NET vs Windows.Data.Json

Windows 8 introduces a new way to work with JSON via the Windows.Data.Json namespace. Similar to LINQ to JSON in Json.NET it defines classes that can be used to parse values, strings, objects, and arrays from JSON text or serialize value types into JSON text.

Below is a comparison of Json.NET’s LINQ to JSON to Window 8’s Windows.Data.Json.

Creating JSON

The big difference between the two libraries when creating JSON is Windows.Data.Json requires string/integer/double values to be explicitly converted to JsonValue objects.

Note that there is a weird limitation to creating JSON with Windows.Data.Json: it doesn’t allow you to set properties to null or have null array values.

// Windows.Data.Json
// -----------------
JsonObject jsonObject = new JsonObject
  {
    {"CPU", JsonValue.CreateStringValue("Intel")},
    {"Drives", new JsonArray {
        JsonValue.CreateStringValue("DVD read/writer"),
        JsonValue.CreateStringValue("500 gigabyte hard drive")
      }
    }
  };
string json1 = jsonObject.Stringify();
 
// LINQ to JSON
// ------------
JObject jObject = new JObject
  {
    {"CPU", "Intel"},
    {"Drives", new JArray {
        "DVD read/writer",
        "500 gigabyte hard drive"
      }
    }
  };
string json2 = jObject.ToString();

Querying JSON

Windows.Data.Json requires a value to be cast to its exact type with the GetObject/GetArray methods before it can be used, making Windows.Data.Json’s code verbose compared to LINQ to JSON.

string json = @"{
  ""channel"": {
    ""title"": ""James Newton-King"",
    ""link"": ""http://james.newtonking.com"",
    ""description"": ""James Newton-King's blog."",
    ""item"": [
      {
        ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
        ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
        ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
        ""category"": [
          ""Json.NET"",
          ""CodePlex""
        ]
      }
    ]
  }
}";
 
// Windows.Data.Json
// -----------------
JsonObject jsonObject = JsonObject.Parse(json);
string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();
 
// LINQ to JSON
// ------------
JObject jObject = JObject.Parse(json);
string itemTitle2 = (string)jObject["channel"]["item"][0]["title"];

Performance

Json.NET is slightly slower at writing JSON than Windows.Data.Json but considerably faster parsing.

Things aren’t as happy as they used to be down here at the unemployment office. Joblessness is no longer just for philosophy majors. Useful people are starting to feel the pinch.

Converting Between LINQ to JSON and Windows.Data.Json

Json.NET supports converting between the types of the two libraries. Use FromObject to convert a Windows.Data.Json value to LINQ to JSON and use ToObject to convert LINQ to JSON to Windows.Data.Json.

JsonObject jsonObject = new JsonObject
  {
    {"CPU", JsonValue.CreateStringValue("Intel")},
    {"Drives", new JsonArray {
        JsonValue.CreateStringValue("DVD read/writer"),
        JsonValue.CreateStringValue("500 gigabyte hard drive")
      }
    }
  };
 
// convert Windows.Data.Json to LINQ to JSON
JObject o = JObject.FromObject(jsonObject);
 
// convert LINQ to JSON to Windows.Data.Json
JArray a = (JArray)o["Drives"];
JsonArray jsonArray = a.ToObject<JsonArray>();

Json.NET 4.5 Release 8 – Multidimensional Array Support, Unicode Improvements

Multidimensional Array Support

Json.NET now supports serializing and deserializing multidimensional arrays. There isn't anything you need to do, if one of your types has a multidimensional array property It Just Works™.

string[,] famousCouples = new string[,]
  {
    { "Adam", "Eve" },
    { "Bonnie", "Clyde" },
    { "Donald", "Daisy" },
    { "Han", "Leia" }
  };
 
string json = JsonConvert.SerializeObject(famousCouples, Formatting.Indented);
// [
//   ["Adam", "Eve"],
//   ["Bonnie", "Clyde"],
//   ["Donald", "Daisy"],
//   ["Han", "Leia"]
// ]
 
string[,] deserialized = JsonConvert.DeserializeObject<string[,]>(json);
 
Console.WriteLine(deserialized[3, 0] + ", " + deserialized[3, 1]);
// Han, Leia

Unicode Performance Improvements

Prior versions of Json.NET allocated a new array and string object to the heap for every Unicode character; a potentially expensive situation if your application is writing a lot of Unicode characters.

This release improves Unicode serialization so that Json.NET will only allocate a single array for all Unicode text and then writes the text directly to the underlying output stream. These changes improve Json.NET performance of Unicode intensive objects by about 20% and significantly reduces the time spent doing garbage collection.

Changes

Here is a complete list of what has changed since Json.NET 4.5 Release 7.

  • New feature - Serialize and deserialize multidimensional arrays
  • New feature - Members on dynamic objects with JsonProperty/DataMember will now be included in serialized JSON
  • New feature - LINQ to JSON load methods will read past preceding comments when loading JSON
  • New feature - Improved error handling to return incomplete values upon reaching the end of JSON content
  • Change - Improved performance and memory usage when serializing Unicode characters
  • Change - The serializer now creates objects using GetUninitializedObject when deserializing a Serializable type
  • Fix - Added SecurityTransparent attribute to WinRT build
  • Fix - Fixed infinite loop error caused by error handling upon reaching the end of JSON content

Links

Json.NET CodePlex Project

Json.NET 4.5 Release 8 Download – Json.NET source code and assemblies

Json.NET 4.5 Release 5 – JsonProperty enhancements

JsonProperty enhancements

JsonPropertyAttribute now has options on it to customize a property’s collection items. When ItemConverter, ItemIsReference, ItemTypeNameHandling or ItemReferenceLoopHandling is set on JsonProperty and the property’s type is a collection then those settings will be applied to every collection item.

public class Event
{
  public string EventName { get; set; }
  public string Venue { get; set; }
 
  [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
  public IList<DateTime> Performances { get; set; }
}

Usage:

Event e = new Event
  {
    EventName = "Blackadder III",
    Venue = "Gryphon Theatre",
    Performances = new List<DateTime>
      {
        DateTime.Parse("8 Tue May 2012, 6:30pm"),
        DateTime.Parse("9 Wed May 2012, 6:30pm"),
        DateTime.Parse("10 Thu May 2012, 8:00pm")
      }
  };
 
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
//{
//  "EventName": "Blackadder III",
//  "Venue": "Gryphon Theatre",
//  "Performances": [
//    new Date(1336458600000),
//    new Date(1336545000000),
//    new Date(1336636800000)
//  ]
//}    

Changes

Here is a complete list of what has changed since Json.NET 4.5 Release 4.

  • New feature - Added ItemIsReference, ItemReferenceLoopHandling, ItemTypeNameHandling, ItemConverterType to JsonPropertyAttribute
  • New feature - Added ItemRequired to JsonObjectAttribute
  • New feature - Added Path to JsonWriterException
  • Change - Improved deserializer call stack memory usage
  • Change - Moved the PDB files out of the NuGet package into a symbols package
  • Fix - Fixed infinite loop from an input error when reading an array and error handling is enabled
  • Fix - Fixed a base object error not being handled when deserializing

Links

Json.NET CodePlex Project

Json.NET 4.5 Release 5 Download – Json.NET source code, documentation and binaries