I have JSON that looks like this: (and I do not control this data structure)
{
"Quest":"To seek the Holy Grail",
"FavoriteColor":"Blue",
"Mother":{
"name":"Eve",
"dob":"1/1/1950"
},
"Father":{
"name":"Adam",
"dob":"2/1/1950"
},
"Siblings":[
{
"name":"Abel",
"dob":"1/1/1980"
},
{
"name":"Kain",
"dob":"3/1/1981"
}
]
}
I have written code to use the Newtonsoft JSON SelectToken
method to look up the names of the mother, father, and siblings and print them on the screen:
using System;
using Newtonsoft.Json.Linq;
namespace JsonTest
{
class Program
{
const string JSON = @"{
""Quest"":""To seek the Holy Grail"",
""FavoriteColor"":""Blue"",
""Mother"":{
""name"":""Eve"",
""dob"":""1/1/1950""
},
""Father"":{
""name"":""Adam"",
""dob"":""2/1/1950""
},
""Siblings"":[
{
""name"":""Abel"",
""dob"":""1/1/1980""
},
{
""name"":""Kain"",
""dob"":""3/1/1981""
}
]
}";
static void Main(string[] args)
{
JObject jObject = JObject.Parse(JSON);
JToken mother = jObject.SelectToken("Mother");
JToken father = jObject.SelectToken("Father");
JToken siblings = jObject.SelectToken("Siblings");
Console.WriteLine("Mother: " + mother.ToString());
Console.WriteLine("Father: " + father.ToString());
Console.WriteLine("Siblings: " + siblings.ToString());
}
}
}
I pass three different arguments to SelectToken
to select three different parts of the document into three different JToken variables. It should be noted that two of those variables contain single names, but the last contains an array of names.
I have been asked to do a task where I will need the values for Mother, Father, and Siblings all in one array.
In short, I want to write something like this:
JToken family = jObject.SelectToken("_____");
Console.WriteLine(family.ToString());
and the result should be this:
[
{
"name":"Eve",
"dob":"1/1/1950"
},
{
"name":"Adam",
"dob":"2/1/1950"
},
{
"name":"Abel",
"dob":"1/1/1980"
},
{
"name":"Kain",
"dob":"3/1/1981"
}
]
Is there a value I can fill in the blank for SelectToken
to make this happen? I already have a system where data is selected with a single call to SelectToken
, so it will make things much easier if I don't have to write in an exception to make multiple calls.