Json.NET 4.0 Release 1 – .NET 4 and Windows Phone support

By popular demand: Json.NET 4.0! This is the first Json.NET release to target .NET 4 and integrates the many new features added in the latest version of .NET. Behind the scenes Json.NET’s source code has been upgraded to VS2010.

Other major changes in this release are two new builds and the removal of an existing build. Removed is Compact Framework. VS2010 no longer supports Compact Framework so 3.5 r8 will be its last release if you are targeting the Compact Framework. New on the other hand are builds for .NET 3.5 (the main build has been upgraded to .NET 4) and Windows Phone.

Windows Phone dll

Json.NET 4.0 comes with a Windows Phone specific dll, compiled using the Windows Phone tools. The Silverlight build now targets Silverlight 4 so is no longer compatible with Windows Phone. A couple of little bonuses of Windows Phone having its own dll is that it doesn’t prompt with a warning when added. There is also some additional XML support. Because LINQ to XML is included in Windows Phone by default (it is an add-on dll for Silverlight) the Json.NET Windows Phone build has some XML features that are missing out of Silverlight release.

Dynamic

One of the more interesting features introduced in .NET 4 is the dynamic keyword. Succinctly it allows variables and members to be statically typed as dynamic. The .NET type system that you know and love remains but operations involving dynamic values are evaluated at runtime.

Json.NET 4.0 adds support for dynamic in a couple of areas. The first and less visible of the two is in the JsonSerializer. Because there is no static list of fields or properties for a dynamic type the serializer interrogates the value for its members prior to serializing and deserializing. The end result is serializing should Just Work for any type that implements IDynamicMetaObjectProvider.

dynamic value = new DynamicDictionary();
 
value.Name = "Arine Admin";
value.Enabled = true;
value.Roles = new[] {"Admin", "User"};
 
string json = JsonConvert.SerializeObject(value, Formatting.Indented);
// {
//   "Name": "Arine Admin",
//   "Enabled": true,
//   "Roles": [
//     "Admin",
//     "User"
//   ]
// }
 
dynamic newValue = JsonConvert.DeserializeObject<DynamicDictionary>(json);
 
string role = newValue.Roles[0];
// Admin

The second area with new dynamic support is LINQ to JSON. JObject properties can be accessed like that were members on a type and JValues can be converted to .NET types without casting, saving you the consumer precious KLOCs.

JObject oldAndBusted = new JObject();
oldAndBusted["Name"] = "Arnie Admin";
oldAndBusted["Enabled"] = true;
oldAndBusted["Roles"] = new JArray(new[] { "Admin", "User" });
 
string oldRole = (string) oldAndBusted["Roles"][0];
// Admin
 
 
dynamic newHotness = new JObject();
newHotness.Name = "Arnie Admin";
newHotness.Enabled = true;
newHotness.Roles = new JArray(new[] { "Admin", "User" });
 
string newRole = newHotness.Roles[0];
// Admin

NuGet

Json.NET has a NuGet package available from the official NuGet package source. Right now it has Json.NET 3.5 Release 8 but expect it to be updated to Json.NET 4.0 in a couple of days.

I'm disrespectful to dirt! Can you see that I am serious? Out of my way, all of you! This is no place for loafers! Join me or die! Can you do any less?

JSON Schema

Json.NET’s JSON Schema implementation has been updated to match version 3 of the specification. Notable new additions are patternProperties, exclusiveMinimum and exclusiveMaximum. Also new is the removal of optional which has been replaced with required. If you are using JSON Schema then you should check whether this change effects your schemas.

BSON Binary

The BSON spec has changed how binary values inside BSON should be written, deprecating the way Json.NET use to write binary values. Json.NET has been changed to use the new method.

Also worth noting is Json.NET had a bug with how it use to read and write the old binary values – this is fixed in Json.NET 4.0 but existing incorrect binary values will remain. Setting JsonNet35BinaryCompatibility on BsonReader will fix reading any existing BSON after upgrading to 4.0 but because of this bug and the change in how the spec says BSON binary values should be written it is recommended to update existing BSON to keep things consistent. This can be done by setting compatibility flag to true, reading BSON and then writing it back out again.

These changes only effect BSON that has binary values (i.e. byte arrays) written inside BSON.

Changes

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

  • New feature - Added Windows Phone 7 project
  • New feature - Added dynamic support to LINQ to JSON
  • New feature - Added dynamic support to serializer
  • New feature - Added INotifyCollectionChanged to JContainer in .NET 4 build
  • New feature - Added ReadAsDateTimeOffset to JsonReader
  • New feature - Added ReadAsDecimal to JsonReader
  • New feature - Added covariance to IJEnumerable type parameter
  • New feature - Added XmlSerializer style Specified property support
  • New feature - Added support for deserializing to JToken
  • New feature - Added CamelCaseText flag to StringEnumConverter
  • New feature - Added WriteArrayAttribute to XmlNodeConverter to include an attribute to help round tripping JSON and XML
  • New feature - Added OmitRootObject to XmlNodeConverter to skip writing the root JSON object when converting XML
  • New feature - Added DeepClone and ICloneable implementation to JToken
  • New feature - Added JSON schema PatternProperties, ExclusiveMinimum and ExclusiveMaximum for JSON schema spec 3
  • New feature - Added .NET 3.5 project
  • Change - Updated source code to VS2010
  • Change - Updated main project to .NET 4
  • Change – Updated Silverlight project to Silverlight 4
  • Change - ICustomTypeDescriptor implementation moved to JObject
  • Change - Improved error message when converting JSON with an empty property to XML
  • Change - JSON schema Required replaced with Optional, as defined in JSON schema spec 3
  • Change - JSON schema MaxDecimals replaced with DivisibleBy, as defined in JSON schema spec 3
  • Remove - Compact Framework project removed. Compact Framework is not supported in VS2010
  • Remove - JTypeDescriptionProvider and JTypeDesciptor removed
  • Fix - BSON writing of binary values fixed. Added JsonNet35BinaryCompatibility flag for reading existing incorrect BSON binary values
  • Fix - Timezone information no longer lost when deserializing DateTimeOffsets
  • Fix – Decimal precision no longer lost when deserializing decimals
  • Fix - SelectToken no longer skips the last project name when it is a single character
  • Fix – Deserializing structs correctly set when reusing existing values is true
  • Fix – Private getter/setters on base classes are now correctly accessible
  • Fix – Nullable structs correctly deserialize
  • Fix - JSON Schema option label now written correctly
  • Fix – Deserializing a DataSet when it is a property of another object no longer breaks
  • Fix - JToken Load and Parse methods now check that content is complete

Links

Json.NET CodePlex Project

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

kick it on DotNetKicks.com

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