Json.NET 4.5 Release 1 - ISO dates, Async, Metro build

This is the first major release of Json.NET 4.5. Read on for the details.

ISO Dates

Json.NET now writes dates as an ISO 8601 string by default instead of Microsoft’s format.

The reason for the change is the ISO format is becoming the standard for JSON libraries. All major browsers output an ISO date from the JSON.stringify function for example. Other benefits are the ISO 8601 standard is human readable unlike Unix ticks and the format is better at handling time zones.

This is a breaking change but there is option to make dates go back to what they were called DateFormatHandling. Setting DateFormatHandling on either the JsonSerializer or JsonSerializerSettings to MicrosoftDateFormat will keep your dates nice and Unix ticky.

Async Serialization

There are new helper methods on JsonConvert for serializing and deserializing JSON asynchronously.

private static async Task<ExpensiveViewModel> CreateExpensiveViewModel()
{
  // these happen simultaneously
  var people = JsonConvert.SerializeObjectAsync(GetPeople());
  var products = JsonConvert.SerializeObjectAsync(GetProducts());
 
  return new ExpensiveViewModel
  {
    People = await people,
    Products = await products
  };
}

Metro Build

Json.NET now supports Windows 8 Metro applications (i.e. WinRT). Since WinRT is still in beta, and because reflection has to be rewritten for this build (booo) there maybe bugs in more esoteric serialization scenarios.

Assembly Versioning

I’m going to experiment with only updating the assembly version at major version changes (i.e. 4.5.0.0) and letting the assembly file version keep the true version number, similar to what the ASP.NET team do with MVC assemblies. Breaking changes will only happen on major version changes.

Hopefully this should reduce the amount of assembly binding redirecting going on for everyone.

And other stuff

A sweet bug fix means that a performance test now runs 70,000% faster, the path of the current JSON location is now on JsonReader and exceptions for easier debugging and a potential security hole when serializing ISerializable types in partial trust has been closed.

Changes

Here is a complete list of what has changed since Json.NET 4.0 Release 8.

  • New feature - Windows 8 Metro build
  • New feature - JsonTextReader automatically reads ISO strings as dates
  • New feature - Added DateFormatHandling to control whether dates are written in the MS format or ISO format, with ISO as the default
  • New feature - Added DateTimeZoneHandling to control reading and writing DateTime time zone details
  • New feature - Added async serialize/deserialize methods to JsonConvert
  • New feature - Added Path to JsonReader/JsonWriter/ErrorContext and exceptions with the JSON path of the current position
  • New feature - Added collection type to JsonArrayContract
  • New feature - Added dictionary key type and dictionary value type to JsonDictionaryContract
  • New feature - Added reader/writer specific Formatting, DateFormatHandling and DateTimeZoneHandling to JsonSerializerSettings
  • New feature - Added ReadAsDate and ReadAsString to JsonReader
  • New feature - Added IgnoreSerializableInterface to DefaultContractResolver
  • Change - Dates are now serialized as the ISO format by default
  • Change - The ReadAsXXX methods on JsonReader now return null at the end of an array instead of throwing an error
  • Change - JsonReaders now to set TokenType to JsonToken.None after finishing content
  • Change - Deserializing will fallback to use a private default constructor
  • Change - The error message when deserializing a JSON object/array onto the wrong kind of type is more descriptive
  • Change - Serializing ISerializable types under partial trust now errors to fix potential security issue
  • Fix - Fixed reading scientific notation numbers with no decimal point
  • Fix - Fixed LinqBridge collision error in .NET 2.0 by moving types to a different namespace
  • Fix - Fixed error when deserializing nullable types with no content
  • Fix - Fixed JObject.Keys null reference error when the object has no items
  • Fix - Fixed error handling when failing to parse array content
  • Fix - Fixed error handling when there are missing required properties
  • Fix - Fixed performance issue when building deeply nested JSON to LINQ to JSON objects

Links

Json.NET CodePlex Project

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

Json.NET 4.0 Release 8 – Bug fixes

This is a relatively minor release that fixes all outstanding bugs and adds a couple of enhancements.

NuGet Silverlight/Windows Phone Assemblies No Longer Strong-Named

The big change this release is that the Silverlight/Windows Phone NuGet assemblies are no longer strong-named.

Unfortunately Silverlight/Windows Phone applications do not support redirecting strong-named assemblies like normal .NET apps do via <assemblyBinding> configuration. If a Silverlight or Windows Phone application uses two libraries that each reference a different version of Json.NET then the only solution is to get the source code for the libraries and recompile them yourself to use the same version of Json.NET – not ideal.

From 4.0.8 the NuGet assemblies for Silverlight/Windows Phone are no longer strong-named. If you do need strong-named versions of Json.NET for SL/WP then they are still available in the Json.NET zip download from CodePlex in the Bin\Silverlight\Signed and Bin\WindowsPhone\Signed zip folders. I don’t recommend using them with reusable SL/WP libraries because of the reasons above.

Json.NET Assembly Redirection

In case you ever do end up with multiple libraries that reference different versions of Json.NET in a normal .NET application, here is the configuration to fix your application use one version of Json.NET:

<runtime>
  <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentityname="Newtonsoft.Json"publicKeyToken="30ad4fe6b2a6aeed" />
      <bindingRedirectoldVersion="1.0.0.0-4.0.0.0"newVersion="4.0.8.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

Update newVersion as needed to the version of Json.NET you are using. This can be found in Visual Studio by right-clicking on Newtonsoft.Json reference and selecting Properties.

Mr. Simpson, you're smarter than you look, or sound, or our best testing indicates.

Changes

Here is a complete list of what has changed since Json.NET 4.0 Release 6 (if you’re curious where v7 is, it was a minor release to fix a couple of urgent bugs).

  • New feature - Added VersionConverter for System.Version
  • New feature - Added a JSON schema IsValid overload that returns a list of error messages
  • Change - NuGet Silverlight/Windows Phone assembies are no longer strong-named
  • Fix - Fixed Json.NET attributes on nullable struct properties not being used
  • Fix - Fixed deserializing nullable enums
  • Fix - Fixed JsonConstructor incorrectly being allowed on properties
  • Fix - Fixed empty string being changed to null when deserializing object properties
  • Fix - Fixed not replacing ignored properties when resolving an object's contract
  • Fix - Fixed JsonReader.ReadAsDateTimeOffset throwing an incorrect error message
  • Fix - Fixed error when converting XML to JSON with a default namespace
  • Fix - Fixed JsonValidatingReader.ReadAsBytes throwing an exception
  • Fix - Fixed a unit test failing because of the running computer’s timezone

Links

Json.NET CodePlex Project

Json.NET 4.0 Release 8 Download – Json.NET source code, documentation and binaries

Json.NET 4.0 Release 6 – Serialization Performance

The big feature of this release is improved performance. For the first time in a couple of years I’ve sat down and benchmarked, profiled and tuned Json.NET.

And now, in the spirit of the season: start shopping. And for every dollar of Krusty merchandise you buy, I will be nice to a sick kid. For legal purposes, sick kids may include hookers with a cold.

For all its features Json.NET was already fast but there are improvements in JsonTextReader which I rewrote and object deserilization. Json.NET is faster than both .NET framework JSON serializers in all scenarios again.

Improved error messages

One of the nice features of JsonTextReader is that it keeps track of its current line number and line position and includes that information when it encounters bad JSON.

This release adds that line number and position information to deserialization errors. Now deserialization should be much easier to troubleshoot.

string json = @"[
  1,
  2,
  3,
  null
]";
 
List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
// Error converting value {null} to type 'System.Int32'. Line 5, position 7.

Worst. Bug. Ever. Fixed.

Visual Studio Ultimate Edition has a feature called Intellitrace. Intellitrace and Json.NET didn’t get along. After a year of at first being unsure why only some people were getting the error, and then not knowing what exactly why Intellitrace was breaking Json.NET, I finally nailed it down to one three line method that Intellitrace didn’t like. Fixed... finally.

Changes

Here is a complete list of what has changed since Json.NET 4.0 Release 4 (if you’re curious where v5 is, it was just one fix for Windows Phone Mango and NuGet).

  • New feature - Added line number information to deserialization errors
  • New feature - Added ReadAsInt32 to JsonReader
  • New feature - Added BinaryReader/BinaryWriter constructor overloads to BsonReader/BsonWriter
  • Change - JsonTextReader error message when additional JSON content found is more descriptive
  • Fix - Removed unused utility methods
  • Fix - Fixed elusive Intellitrace runtime destabilization error
  • Fix - Fixed internal exception thrown when deserializing Decimal/DateTimeOffset/Byte lists
  • Fix - Fixed potential multi-threading serializing issue
  • Fix - Fixed serializing types that hides a base classes property with a proeprty of the same name
  • Fix - Fixed BsonReader to use BinaryReader instead of base stream
  • Fix - Fixed referencing the NuGet package from Windows Phone 7.1 projects

Links

Json.NET CodePlex Project

Json.NET 4.0 Release 6 Download – Json.NET source code, documentation and binaries

Json.NET 4.0 Release 4 – Bug fixes

This release contains bug fixes and some minor changes.

Custom type names with TypeNameHandling

Note that support for custom type names was added in a previous Json.NET release.

One commonly asked for feature is the ability to customize the value of the $type property when using TypeNameHandling. Fortunately new in .NET 4 is the virtual SerializationBinder.BindToName method that translates a Type to a custom string.

To customize the $type property in Json.NET just create a class that inherits from SerializationBinder and override the BindToName and the BindToType methods with your custom naming logic. The example SerializationBinder example below serializes types to just their name without any namespace or assembly information, those details are passed into the binder itself via a constructor parameter and used during deserialization.

public class TypeNameSerializationBinder : SerializationBinder
{
  public string TypeFormat { get; private set; }
 
  public TypeNameSerializationBinder(string typeFormat)
  {
    TypeFormat = typeFormat;
  }
 
  public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
  {
    assemblyName = null;
    typeName = serializedType.Name;
  }
 
  public override Type BindToType(string assemblyName, string typeName)
  {
    string resolvedTypeName = string.Format(TypeFormat, typeName);
 
    return Type.GetType(resolvedTypeName, true);
  }
}

The simplest way to use a custom serialization binder is with JsonConvert and JsonSerializerSettings.

TypeNameSerializationBinder binder = new TypeNameSerializationBinder("YourAppNamespace.{0}, YourAppAssembly");
 
IList<object> values = new List<object>
  {
    new Customer
      {
        Name = "Caroline Customer"
      },
    new Purchase
      {
        ProductName = "Elbow Grease",
        Price = 5.99m,
        Quantity = 1
      }
  };
 
string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
{
  TypeNameHandling = TypeNameHandling.Auto,
  Binder = binder
});
 
//[
//  {
//    "$type": "Customer",
//    "Name": "Caroline Customer"
//  },
//  {
//    "$type": "Purchase",
//    "ProductName": "Elbow Grease",
//    "Price": 5.99,
//    "Quantity": 1
//  }
//]

To deserialize just reuse the custom SerializationBinder with DeserializeObject.

Changes

Here is a complete list of what has changed since Json.NET 4.0 Release 3.

  • Change - JsonTextReader.Culture is now CultureInfo.InvariantCulture by default
  • Change - KeyValurPairConverter no longer depends on the order of the key and value properties
  • Change - Time zone conversions now use new TimeZoneInfo instead of TimeZone
  • Fix - Fixed boolean values sometimes being capitalized when converting to XML
  • Fix - Fixed error when deserializing ConcurrentDictionary
  • Fix - Fixed serializing some Uris returning the incorrect value
  • Fix - Fixed occasional error when converting non-long integer properties to XML
  • Fix - Fixed deserializing byte arrays with type name information
  • Fix - Fixed flag enum items not being correctly camel cased
  • Fix - Fixed JsonValidatingReader validating the first array item twice
  • Fix - Fixed JsonSchema not correctly validating integers as a subset of decimal
  • Fix - Fixed bad BSON when writing long strings of complex UTF8 characters
  • Fix - Fixed error not being raised for additional content in JSON string for JArray.Parse and JObject.Parse
  • Fix - Fixed DataTableConverter including nulls with NullValueHandling.Ignore

Links

Json.NET CodePlex Project

Json.NET 4.0 Release 4 Download – Json.NET source code, documentation and binaries