Widunder
Widunder

Reputation: 295

Get values out of JSON when first field's name is dynamic

What would be the best way of retrieving values here as a List<string>? I cannot convert it into concrete class since the name of the root object will always change.

The following is the json:

{"356bfd81-0fd7-45ef-a768-d0d1b6f63c1b":{"TableEntry":[{"Id":"169b47a6-1f94-4103-959b-785096960927"},{"Id":"e07885eb-0db5-4134-8890-681a8fa63a8e"},{"Id":"12fe4ad1-cf22-40ea-840f-356bfd0b6ce2"},{"Id":"1a4ec0d6-f2b6-43e2-adc6-7350ea0dc9c7"},{"Id":"16cbecd7-80a5-43f8-b83a-54816b2bff87"},{"Id":"c1df10c6-0628-4844-9024-f43f9a3605c7"},{"Id":"bdced1ae-203c-4c9e-bc8e-d4d74b9008f3"},{"Id":"50e9e85e-cd3c-4a49-820d-607960e81e87"},{"Id":"1869b251-ffce-474e-bedb-3f37a07e36e2"},{"Id":"8e8c432b-0d7a-4397-b96b-c77a93692941"}]}}

I do not know how I can bypass the first root object to get the List of Ids that I'm after.

So far I have tried JObject.Parse() But that allows me only to use .First property. But that causes my variable to look like myObject.First.First.First. Which is not ideal.

I have also tried casting it into dynamic. But that's no good either, I cannot go myObject.TableEntry - it doesn't see it. And I can't seem to get even passed the first point here, as myObject[0] would throw an exception.

Any suggestions how can I get List<string> of Ids from such json? Thank you.

Upvotes: 1

Views: 103

Answers (2)

Tyress
Tyress

Reputation: 3653

If these are the only objects with a key as Id, one other way is to use Descendants().

JToken Id = null;
var jsonObject = JObject.Parse(json);
List<string> IDs = jsonObject.Descendants().Where(x => d is JObject && ((JObject)d).TryGetValue("Id", out Id)).Select(_=>Id.Value<string>()).ToList();

Upvotes: 0

Nkosi
Nkosi

Reputation: 247153

use a Dictionary<string,YourModel> where Your model

public class MyModel {
    public TableEntry[] TableEntry { get; set; }
}

public class TableEntry {
    public string Id { get; set; }
}

Once parsed

var data = JsonConvert.DeserializeObject<Dictionary<string,MyModel>>(json);

you can easily get the data

List<string> ids = data.First().Value.TableEntry.Select(entry => entry.Id).ToList();

or

List<string> ids = data
    .SelectMany(kvp => kvp.Value.TableEntry.Select(entry => entry.Id))
    .ToList();

if there are multiple dynamic keys

Upvotes: 3

Related Questions