Saturday, February 23, 2013

JSON.net support C# keyword dynamic

JSON.net supports the C# keyword dynamic.  Let's start with the following JSON dataset. .
 
{ 
    "LastName"  : "Smith",
    "FirstName" : "John",
    "Age"       : 32,
    "Male"      : true,
    "BirthDate" : "1962-12-11T00:00:00Z",
    "Other"     : null
}
The function JObject.Parse() returns a JObject that we will store into a C# dynamic object. Now we can dynamically access all properties defined in the JSON object (No need to define a class. Am I in JavaScript or what?).
 
dynamic person = JObject.Parse(System.IO.File.ReadAllText("Person.json"));   
Console.WriteLine(person.LastName);
Console.WriteLine(person.FirstName); 
Console.WriteLine(person.Age);
Console.WriteLine(person.Male);
Console.WriteLine(person.BirthDate);
We can also add a new property on the fly and request the JSON representation.
person.Loaded = true; // New property
Console.WriteLine(JsonConvert.SerializeObject(person, Formatting.Indented));
 
{
  "LastName": "Smith",
  "FirstName": "John",
  "Age": 32,
  "Male": true,
  "BirthDate": "1962-12-11T00:00:00Z",
  "Other": null,
  "Loaded": true
}
Nested object and array are supported. Trying to access a undefined property will return null.
Thanks to james newton king .

1 comment:

  1. Recently i ran into your website and so are already reading along. I think I’d leave my first comment. I don’t understand what to share with the exception that I’ve enjoyed reading. Nice blog. For certain i will keep visiting your blog really often

    PIC scheme

    ReplyDelete