[英]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.我想以相同的 position 顺序创建嵌套的 json object。
End result would be:最终结果将是:
{
"a":{
"b":{
"c":{
"d":{
}
}
}
}
}
or或者
{
"x":{
"y":{
"z":{
}
}
}
}
You can compose JObject
to obtain what you want:您可以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.