简体   繁体   中英

C# Dynamically create JSON with nested objects from array of strings

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":{
         }
      }
   }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM