0

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": "[email protected]",
    "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?

4
  • I'd expect it to be pretty simple - it looks like you've already got the code to get the first preference (without the [0] at the end it would be all the preferences). So what's going wrong with the code you've got? Commented Jul 8, 2014 at 6:00
  • The actual json is slightly different(updated question ) , so i used the code and if i try to Parse without[0] it returns error "Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type Newtonsoft.Json.Linq.JObject'." And if i change the JObject to JArray it returns again exception is not a valid JArray to parse Commented Jul 8, 2014 at 6:15
  • Well the preferences itself is a JArray, but you can ask for any element within that JArray. So what exactly are you trying to do with the preferences, what code have you tried, and what went wrong? It's hard to help you without concrete requirements. Commented Jul 8, 2014 at 6:19
  • Please see the code sample i used in question (Now updated) Commented Jul 8, 2014 at 6:28

1 Answer 1

1

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;
    ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

@JMat: Well the code I've given already builds a dictionary of names and values. What do you need to do that that doesn't achieve?
Yes it helped to get the values from JSON object. I did few more modifications in code so i can loop through all child and sub childs. (answer edited )
@JMat: Please don't edit other people's answers to add large chunks of code. That should be an edit on your question, if anything (or a new answer) - although it's not clear that it's useful for other readers, to be honest.
will follow to do the way in my future posts. thanks for helping to fix the current issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.