1

I'm just an amateur in C# programming. Now i have a JSON data that looks like following

{
  type: "xxx",
  width: "xxx",
  dataSource: {
      "chart": {
          "caption": "xxx"
       },
      "data": [
       {},
       {} 
      ]
  } 
}

I'm having the whole data as escaped string. now after Unescape when I'm using JavaScriptSerializer as follows

var data = ser.Deserialize<Dictionary<String, Object>>(chartData);

I'm able to get the "type", "width" as

data["width"]
data["type"]

Now I have to get the value of "caption". Any suggestion how to get that, I believe the dictionary structure need to be changed but I'm stacked for my lack of knowledge in C#

Sahasrangshu Guha
  • 672
  • 2
  • 11
  • 29

1 Answers1

2

If you know the object's scheme you man want to create a class that represents in and then deserialize the json into it:

YourKnownClass obj = JsonConvert.DeserializeObject<YourKnownClass>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);

Another option is by using a dynamic type (There is no good reason using a dynamic object if you know the schema and can create a matching C# class. This has a performance impact as well):

dynamic obj = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(obj.dataSource.chart.caption.Value);

BTW, In this example i'm using json.net which is a popular library.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • 2
    You should mention that you use an external library called Json.NET instead of the built-in deserializer. – fero Feb 08 '16 at 07:23