JSON Array to C# Using Json.Net

Posted on 20 Nov 2008 Json.Net is a great little library that “makes working with JavaScript and JSON formatted data in .Net simple”. I’ve been using Json.Net for quite some time now, but have restricted my use mostly to building JSON strings in C# and pushing them down to the client. It works well for this, although I'll admit that I don't think that manually building JSON strings in C# will ever be anything other than tedious. Well, today I starting working on a query framework for NPMap, and decided that JSON was the easiest (and most efficient) way to pass parameters for the queries up to the server. You see, the user interface allows the user to query one or more database entities and choose one or more (or all) fields from each entity to include in the query. So I decided to send up an array of JavaScript objects that looked a little something like this:
[
  {
    "entity": "Battlefields",
    "fields": "BattlefieldCode, BattlefieldName, StartDate, EndDate"
  },
  {
    "entity": "CivilRightsSites",
    "fields": "SiteId, StartDate, EndDate"
  }
]
But how to deserialize that JSON string into something I can use on the server? Enter Json.Net. First I created a class to hold each of the JavaScript objects:
public class QueryEntity
{
     public string entity {get; set; }
     public string fields {get; set; }
}
Next I deserialized the JSON string into a list of QueryEntity objects:
List<QueryEntity> entities = (List<QueryEntity>) JavaScriptConvert.DeserializeObject(json, typeof(List<QueryEntity>));
And finally I iterated through the objects:
foreach (QueryEntity obj in entities)
{
     string entity = obj.entity;
     string fields = obj.fields;
}
And that's it. Json.Net saves the day again!
« Migrating from BlogEngine.Net to WordPress | Free CDN Hosting for the Ext JS Framework »