4

Given the json string

var testJson = @"{'entry1': {
                       '49208118': [
                          {
                             'description': 'just a description'
                          },
                          {
                             'description': 'another description' 
                          }
                       ],
                       '29439559': [
                          {
                             'description': 'just a description'
                          },
                          {
                             'description': 'another description' 
                          }
                       ]
                     }
                }";

The array value of the key 49208118 can be retrieved by

var root = JToken.Parse(testJson);
var descriptions = root.SelectTokens("..49208118[*]").ToList();

according to this answer.

But how can the whole substructure under entry1 be parsed into a dictionary

 Dictionary<string, JArray> descriptions;

mapping the numerical ids to arrays of JObjects?

3
  • But if the Key is unknown how do you know which element you want to access? Commented May 15, 2018 at 7:33
  • For the sake of this example, we can generalize to n numerical key-value pairs with arbitrary , dynamic numerical keys. Commented May 15, 2018 at 7:35
  • I think, I don't really understand your problem, but wouldn't something like var root = d.SelectToken("$..entry1"); give you such a dictionary? Commented May 15, 2018 at 8:19

2 Answers 2

1

Since question is how you can parse entry1 to Dictionary<string, JArray> - easiest option is:

JToken root = JToken.Parse(testJson);
Dictionary<string, JArray> descriptions = root["entry1"].ToObject<Dictionary<string, JArray>>();

Json.NET allows mixing of .NET classes (Dictionary) and his own classes (JArray) without problems when parsing.

Sign up to request clarification or add additional context in comments.

Comments

1

How about this:

string selector = String.Format("..{0}[*]", yourKey);
var descriptions = root.SelectTokens(selector).ToList();

3 Comments

What is "yourKey" ? Remember, the id is not known in advance. The only thing known is that there is an arbitrary numerical key with an array value.
Do you want to retrieve a flattened array or nested arrays?
The latter: Nested. I.e., a dictionarry { id : descriptions}

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.