Read dynamic json property values using JObject c#

Part of my Json structre is dynacmic array and i want to read it using Json.Net . The json structre is

{
"objects": [{
    "id": "521daea47288c7794c88c923",
    "name": "Rass",
    "email": "ras@hjsh.com",
    "username": "ras",
    "books": [],
    "devices": [],
    "preferences": [
    {
    "name": "key1",
    "value": [
      {
        "id": "val1Id",
        "params": [
          {
            "name": "set1key",
            "value": 0
          },
          {
            "name": "set1key2",
            "value": 0
          },
          {
            "name": "set1key3",
            "value": 0.5
          }
        ]
      },
      {
        "id": "val2Id",
        "params": [
          {
            "name": "set2key",
            "value": 0
          },
          {
            "name": "set2key2",
            "value": 0
          },
          {
            "name": "set2key3",
            "value": 0.5
          }
        ]
      }
    ]
  },
  {
    "name": "language",
    "value": "en_US"
  },
  {
    "name": "page_zoom",
    "value": 1
  }
],
"created": "2013-08-28T08:02:44.000Z"
}],
"meta": {
    "total_count": 1,
    "offset": 0,
    "limit": 1000
}

}

How can i access the set of preferences in my c# code . I gets the preference tag from json using the below code

   var jObject = JObject.Parse(jsonString);
        JObject obj = (JObject)jObject["objects"][0]["preferences"][0];
        string pref = "";
        foreach (var pref_item in obj)
        {
            string key = pref_item.Key;               
           //Here i want to check the Value is of type array, then get each item from Array.
            //If its not an array simply read the value
        }

Now i want to navigate to each preference items , store the name and value properties. If Value is array i want to access each items in that array . How can i do it?

Jon Skeet
people
quotationmark

It's hard to know exactly what you need based on the somewhat vague requirements, but here's some code which will get you a Dictionary<string, JToken> of the preferences:

JArray preferences = (JArray)jObject["objects"][0]["preferences"];
var dictionary = preferences.ToDictionary(x => (string) x["name"],
                                          x => x["value"]);

// For example...
Console.WriteLine(dictionary["language"]); // prints en_US

You can then do whatever you want with the tokens. Anything where the value itself is an array will have have a JArray value. You can test that easily enough:

JToken value = dictionary[key];
JArray array = value as JArray;
if (array != null)
{
    ...
}    

Or:

JToken value = dictionary[key];
if (value.Type == JTokenType.Array)
{
    JArray array = (JArray) value;
    ...
}

people

See more on this question at Stackoverflow