Tuesday, September 23, 2014

How to use .Net Dynamic to parse Json Data in C#

From my previous post How to Convert JSON XML string representation to Object in C#

I show how to define C# objects hierarchy to present the Data structure in the Json.

we can now quick access those data in C# 4.0 with Dynamic that introduced in .net framework 4.0

the step to access the Json data is quiet straight forward

first we need to add a reference to System.Web.Extensions.

second we must add  using System.Web.Script.Serialization;  to the library reference section

the code snippet to deserialize the Json object

var serializer = new JavaScriptSerializer();
var jsonObject= serializer.Deserialize<Dictionary<string, dynamic>>(MyJsonData);



 
I still use the same Json Data from my previous post and set an breakpoint in order to view the jsonObject

{
 "id": "0001",
 "type": "donut",
 "name": "Cake",
 "ppu": 0.55,
 "batters":
  {
   "batter":
    [
     { "id": "1001", "type": "Regular" },
     { "id": "1002", "type": "Chocolate" },
     { "id": "1003", "type": "Blueberry" },
     { "id": "1004", "type": "Devil's Food" }
    ]
  },
 "topping":
  [
   { "id": "5001", "type": "None" },
   { "id": "5002", "type": "Glazed" },
   { "id": "5005", "type": "Sugar" },
   { "id": "5007", "type": "Powdered Sugar" },
   { "id": "5006", "type": "Chocolate with Sprinkles" },
   { "id": "5003", "type": "Chocolate" },
   { "id": "5004", "type": "Maple" }
  ]
}

here is the quick view of jsonObject





No comments:

Post a Comment