Json.NET 4.0 Release 2 – NuGet 1.2 and Dynamic

This release builds on two areas introduced in Json.NET 4.0: NuGet and .NET 4 dynamic support.

NuGet 1.2

I understand. Let us celebrate our agreement with the adding of chocolate to milk. NuGet is fast becoming the preferred way to install libraries in .NET. NuGet 1.2 was recently released and among other improvements it adds support for the Windows Phone.

Json.NET 4.0 Release 2 has been updated to support NuGet 1.2 and Windows Phone – there is nothing you need to do, it should just work. Windows Phone brings Json.NET’s NuGet support up to 7 different frameworks:

  • .NET 4
  • .NET 4 Client Profile
  • .NET 3.5
  • .NET 3.5 Client Profile
  • .NET 2
  • Silverlight 4
  • Windows Phone

Dynamic Improvements

Feedback on the initial release of dynamic support in Json.NET 4.0 was that values didn’t behave as expected. Concatenating two integers would throw an exception for example – less than ideal.

Release 2 adds support for common value operations: comparing, adding, subtracting, multiplying, dividing, incrementing and decrementing all now work like they should.

dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.Price = 4.90m;
product.StockCount = 9000;
product.StockValue = 44100;
 
// All Elbow Grease must go sale!
// 50% off price
 
product.Price = product.Price / 2;
product.StockValue = product.StockCount * product.Price;
product.ProductName = product.ProductName + " (SALE)";
 
string json = product.ToString();
// {
//   "ProductName": "Elbow Grease (SALE)",
//   "Enabled": true,
//   "Price": 2.45,
//   "StockCount": 9000,
//   "StockValue": 22050.0
// }

And More

Like always many smaller features has been added (EnumMemberAttribute serializer support for example) and bugs have been fixed.

Changes

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

  • New feature - Added commonly used primitive value operations to dynamic JValue
  • New feature - Added IComparable to JValue
  • New feature - Added JsonConstructorAttribute to explicitly define which constructor to use during deserialization
  • New feature - Added IFormattable to JValue
  • New feature - Added Load and Parse helper methods to JToken
  • New feature - Added ExpandoObjectConverter that deserializes to primitive values rather than LINQ to JSON objects for ExpandObjects
  • New feature - Added EnumMemberAttribute support to StringEnumConverter
  • New feature - Added CloseInput/CloseOutput to JsonReader/JsonWriter to control whether the underlying stream is closed. Default to true
  • Change - JValue ToString now calls ToString on the internal value
  • Change - NuGet spec file includes client profiles
  • Change - BsonReader/BsonWriter close the underlying stream by default when closed
  • Change - CamelCasePropertyNamesContractResolver updates dictionary and dynamic property names
  • Fix – DefaultValueHandling no longer includes a property when the default value is the same value but a different type
  • Fix – Objects created with paramatized constructors fixed to not set properties that aren't in JSON
  • Fix – Fixed comments in JSON sometimes causing errors when deserializing
  • Fix – Error when reflecting over type that has multiple index properties inherited fixed
  • Fix – Error when reusing JsonSerializer with preserve references enabled fixed
  • Fix – Poor error message when dynamic type cannot be created during deserialization fixed
  • Fix – Error when setting a null value on a dynamic type during deserialization fixed
  • Fix – JsonTextReader.ReadAsDecimal not attempting to convert string values to decimal fixed
  • Fix – Duplicate type name within an assembly error fixed
  • Fix – Deserializing a DataTable property fixed
  • Fix – Code emit error when deserializing interfaces in certain situations fixed
  • Fix – Performance issues when deserializing with partial type names fixed
  • Fix – Deserializing some decimal values on classes with non-default constructors fixed

Links

Json.NET CodePlex Project

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

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