Json.NET 3.5 Release 8 – 3.5 Final

Baring any terrible, terrible damage bugs, Release 8 will be the final 3.5 version of Json.NET.

TypeNameHandling

Json.NET supports including type information in JSON. In the past this was a global flag to include type names for every object. The last release of Json.NET added TypeNameHandling as a flag on JsonPropertyAttribute, allowing type names to be included only for specified values.

public class Message
{
  public string Address { get; set; }
 
  [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  public object Body { get; set; }
}
 
public class SearchDetails
{
  public string Query { get; set; }
  public string Language { get; set; }
}

Any payload of data can be assigned to Message.Body and the type name will be included when it is serialized. Json.NET will automatically deserialize back to that type.

Message message = new Message();
message.Address = "http://www.google.com";
message.Body = new SearchDetails
  {
    Query = "Json.NET",
    Language = "en-us"
  };
 
string json = JsonConvert.SerializeObject(message, Formatting.Indented);
// {
//   "Address": "http://www.google.com",
//   "Body": {
//     "$type": "Newtonsoft.Json.Tests.Serialization.SearchDetails, Newtonsoft.Json.Tests",
//     "Query": "Json.NET",
//     "Language": "en-us"
//   }
// }
 
Message deserialized = JsonConvert.DeserializeObject<Message>(json);
 
SearchDetails searchDetails = (SearchDetails) deserialized.Body;
// Json.NET

TypeNameHandling.Auto

Another new TypeNameHandling feature is TypeNameHandling.Auto. When serializing an object and this flag is set Json.NET will check whether the value of a object matches the property it is declared against. If they aren’t the same, e.g. a property with a type of Mammal has a derived instance of Dog assigned, then Json.NET will automatically include the type name. TypeNameHandling.Auto is pretty neat in that it will ensure that type information isn’t lost for you automatically.

Changes

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

  • New feature - Added TypeNameHandling.Auto to automatically write the type name when a value doesn't match the declared type
  • New feature - Added CLSCompliant attributes
  • New feature - Added Required.Always attribute validation when writing JSON
  • New feature - Added DateTimeKindHandling to BsonWriter to control how a DateTime is converted prior to being serialized
  • New feature - Added SerializeCompilerGeneratedMembers to DefaultContractResolver to control serializing compiler generated fields
  • Change - Improved OverflowException message for integer values larger than an Int64
  • Change - Added interfaces, structs and enums as valid targets of JsonConverterAttribute
  • Change - Added structs as a valid target of JsonObjectAttribute
  • Change - Improved default null and value handing when JSON value is not compatible with property value
  • Change - Serialization attributes now supported in .NET 2.0
  • Change - HtmlColorConverter and System.Drawing.dll dependency removed
  • Fix - Fix reading hexadecimal numbers that contain an e
  • Fix - Generic simple type names no longer include full qualified assembly information for nested generate types
  • Fix - Corrected culture invariance issues
  • Fix - Correct incorrect BSON string reading for multi-byte characters
  • Fix - Fix error when converting a JValue to a compatible type
  • Fix - Fix security exception when generating simple type names on Silverlight
  • Fix - JsonProperty now inherited on overriden properties
  • Fix - JTokenReader.ReadAsBytes no longer errors when reading null token value

Links

Json.NET CodePlex Project

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

Sunday Podcasts 5

Oh, man! We killed Mr. Burns! Mr. Burns is gonna be so mad! Day[9] DailyMy Life of Starcraft

12 years (!!!) after Starcraft and Starcraft II is finally playable. I remember talking with friends just after the first game came out about what we thought the sequel, sure to be ready in a couple of years of course, would be like. So naive 1998 James, so naive.

Beyond being a really fun game to play, Starcraft is also exciting to watch. It is the most successful “e-sport” videogame in the world, with hundreds of pro-gamers making a living off playing Starcraft. Korea in particular loves the game; Starcraft is practically the national sport. Entire TV channels there are dedicated to nothing but pro-gamers playing Starcraft, complete with live commentators.

Actual Starcraft stadium:

Knife goes in, guts come out! That's what Osaka Seafood Concern is all about!

Crazy.

This videocast is by a famous personality in the English speaking Starcraft world, Day[9], and life growing up playing Starcraft. His brother is also heavily involved in the game and I found their journey growing up together really inspirational: from kids in a small town in Kansas playing a videogame on their old home computer, to competing in and winning international Starcraft tournaments around the world, powered by nothing but an incredible love of the game and the support of their mom.

Day[9] Daily #100: My Life of Starcraft

Json.NET 3.5 Release 7 – Biggest Release Ever Edition

Improved BSON Performance

BSON performance has improved markedly in R7. Deserializing is as fast as it was before (i.e. ridiculously fast) but writing BSON has gotten a big boost when writing large complex objects. Using an extreme example this benchmark compares the previous release with the new BSON serializer:

All right, all right, you win. Heh. I see you've played knifey-spooney before.

ShouldSerialize

Did you know that the good old XmlSerializer had support for conditionally deciding what to serialize through ShouldSerialize methods? Me neither.

Not to be outdone, Json.NET is now able to dynamically include and exclude properties the same way. Add a boolean method with the same name as a property and then prefixed the method name with ShouldSerialize. The result of the method determines whether the property is serialized.

In the example below possible circular references are manually handled by testing whether an employee is its own manager before serializing:

public class Employee
{
  public string Name { get; set; }
  public Employee Manager { get; set; }
 
  public bool ShouldSerializeManager()
  {
    return (Manager != this);
  }
}
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
 
joe.Manager = mike;
mike.Manager = mike;
 
string json = JsonConvert.SerializeObject(new []{ joe, mike }, Formatting.Indented);
// [
//   {
//     "Name": "Joe Employee",
//     "Manager": {
//       "Name": "Mike Manager"
//     }
//   },
//   {
//     "Name": "Mike Manager"
//   }
// ]

Build Scripts

Oh, it's no use. I'm never going to find that tree. This whole raid was as useless as that yellow, lemon-shaped rock over there. Wait a minute...there's a lemon behind that rock!Now include with the Json.NET source code are the build scripts used to compile and package Json.NET. A couple of months ago I switched from a clunky old batch script I had been using to Powershell and psake. Compared to past solutions I’ve written using NAnt I’m very happy with the results. XML be gone!

And More

As always there are a crazy number of major (ISerializable support, LINQ to XML XmlConverter support) and minor new features (support for reading octal and hexadecimal numbers from JSON, numerous improvements to the serializer).

Json.NET Release 7 has the biggest change list yet – in fact I had to edit the descriptions of the changes down to fit them all in CodePlex’s release notes size limit!

Changes

Here is a complete list of what has changed since Json.NET 3.5 Release 6.

 

  • New feature - Improved BSON performance
  • New feature - Added WriteOid and WriteRegex to BsonWriter
  • New feature - Added support for ShouldSerialize conditional methods
  • New feature - Added TypeNameHandling to JsonProperty attribute. Allows a type names to be included on an individual property basis
  • New feature - Support for reading octal and hexadecimal numbers from JSON
  • New feature - Added support for enum values to LINQ to JSON
  • New feature - Added TypeNameAssemblyFormat property to JsonSerializer
  • New feature - Added DateTimeConverterBase
  • New feature - Added JsonPrimitiveContract and JsonLinqContract
  • New feature - Added CreateMemberValueProvider method to DefaultContractResolver
  • New feature - INotifyCollectionChanged implemented on JContainer in Silverlight
  • New feature - Included BSON in .NET 2.0, Silverlight and Compact Framework builds
  • New feature - Added ReadRootValueAsArray, DateTimeKindHandling properties to BsonReader
  • New feature - ISerializable support
  • New feature - Added GetSchema, CanRead, CanWrite to JsonConverter
  • New feature - LINQ to XML support added to XmlNodeConverter
  • New feature - SerializeXNode, DeserializeXNode methods added to JsonConvert
  • New feature - Added support for sharing a static cache for contract resolvers inheriting from DefaultControlResolver
  • New feature - Added support for switching between dynamic and late bound reflection for medium trust environments
  • New feature - Support for using implicit/explicit casts when converting a JSON property name to a dictionary value
  • Change – JsonConverter.ReadJson method is now passed the existing value of the property it is converting
  • Change - Built in JsonConverters are resolved once when the contract is created rather than runtime
  • Change - JsonRaw removed and replaced with JRaw
  • Change - Type is now always written as AssemblyQualifiedName
  • Change - Dictionary key serialization falls back to ToString for keys
  • Change - Schema generator now uses JsonContracts to determine schema information
  • Change - Removed the "-" prefix when serializing a JSON constructor - prefix not compatible with XML naming standard
  • Change - When converting JSON to XML using XmlNodeConverter, changed special JSON properties ($id, $ref, $type) to be attributes rather than child elements
  • Fix - Fix dynamic code generation IL verification issues in .NET 4
  • Fix - Fix error when deserializing nullable array
  • Fix - Escape JSON property text
  • Fix - Silverlight serialization security error
  • Fix - Private base members marked with JsonProperty attribute now correctly serialized
  • Fix - Error message when attempting to deserialize custom dictionary with no default constructor
  • Fix - Correctly deserialize empty BSON objects
  • Fix - When a class has a metadata class defined, fall back the original class from the metadata class when attribute not found
  • Fix - Deserialize HashSet<T> without error
  • Fix - Correctly skip ignored JSON properties when deserializing via a non-default constructor
  • Fix - Schema with no properties now correctly validates
  • Fix - Dictionary and array schemas now marked as nullable
  • Fix - Serialize generic dictionary that doesn't implement IDictionary correctly
  • Fix - CustomCreationConverter no longer errors when writing JSON
  • Fix - JsonProperty.Readable and Writable not being correctly set for .NET properties with modified getter/setter visibility
  • Fix - Fix error caused by private properties on a base class when reflecting a type
  • Fix - Correct property CanRead and CanWrite coming back as false when a base class property has a private getter/setter visibility
  • Fix - Fix reading BSON multi byte UTF8 characters
  • Fix - CustomCreationConverter to return null when converting a null JSON value
  • Fix - Fix for possible errors caused by mutable GetHashCode implementations and reference tracking
  • Fix - Fix JTokenReader.ReadAsBytes to read strings as base64 data

Links

Json.NET CodePlex Project

Json.NET 3.5 Release 7 Download – Json.NET source code, documentation and binaries