[英]C# Dynamically create JSON with nested objects from array of strings
所以我有一個動態的字符串數組,例如:
["a","b","c,"d"]
或者
["x","y","z"]
該數組是動態的,可以有可變數量的字符串。
我想以相同的 position 順序創建嵌套的 json object。
最終結果將是:
{
"a":{
"b":{
"c":{
"d":{
}
}
}
}
}
或者
{
"x":{
"y":{
"z":{
}
}
}
}
您可以JObject
以獲得您想要的:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.