Reputation: 75
I have a list of json JTokens:
List<JToken> subjectresults = jObj[jp]["subjects"].Children().ToList();
Note that my jp is var jp = jObj.Properties().First().Name;
because the name is dynamic.
Each of the tokens contains two further items, a url and a name.
I want to get a list of strings that contains just the name value, from this list of jtokens.
So that:
[0]: {{
"url": "https://openlibrary.org/subjects/science",
"name": "Science"
}}
[1]: {{
"url": "https://openlibrary.org/subjects/in_library",
"name": "In library"
}}
Becomes:
{"Science", "In library"}
I can't seem to figure out the syntax. Or alternatively how do I skip the tokens and go right to my list. I didn't strongly type this, because the parent property has the dynamic name, and I only needed a couple of the fields.
Upvotes: 4
Views: 10987
Reputation: 15208
I suppose that subjects-property is Array:
var jObj = JObject.Parse(json);
var jp = jObj.Properties().First().Name;
var subjectresults = jObj[jp]["subjects"]
.Children()
.Select(v => v["name"].Value<string>())
.ToArray();
/*
subjectresults
{string[2]}
[0] [string]:"Science"
[1] [string]:"In library"
*/
The source json:
var json = @"{
""name"": {
""subjects"": [
{
""url"": ""https://openlibrary.org/subjects/science"",
""name"": ""Science""
},
{
""url"": ""https://openlibrary.org/subjects/in_library"",
""name"": ""In library""
}
]
}
}";
Upvotes: 2