Reputation: 13
So I have adynamic array of strings like:
["a","b","c,"d"]
or
["x","y","z"]
The array is dynamic and can have variable number of strings.
I want to create a nested json object, in the same position order of the items.
End result would be:
{
"a":{
"b":{
"c":{
"d":{
}
}
}
}
}
or
{
"x":{
"y":{
"z":{
}
}
}
}
Upvotes: 1
Views: 2619
Reputation: 111860
You can compose JObject
to obtain what you want:
var strs = new string[] { "a", "b", "c", "d" };
JObject jo = new JObject();
JObject parent = jo;
for (int i = 0; i < strs.Length; i++)
{
var jo2 = new JObject();
parent[strs[i]] = jo2;
parent = jo2;
}
// Your final json object is jo
Console.WriteLine(jo);
// string version
string json = jo.ToString(); // or jo.ToString(Formatting.None)
Upvotes: 3