C# 使用字符串数组中的嵌套对象动态创建 JSON
C# Dynamically create JSON with nested objects from array of strings
所以我有一个非动态字符串数组,例如:
["a","b","c,"d"]
或
["x","y","z"]
数组是动态的,可以有可变数量的字符串。
我想创建一个嵌套的 json 对象,与项目的位置顺序相同。
最终结果将是:
{
"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)
所以我有一个非动态字符串数组,例如:
["a","b","c,"d"]
或
["x","y","z"]
数组是动态的,可以有可变数量的字符串。
我想创建一个嵌套的 json 对象,与项目的位置顺序相同。
最终结果将是:
{
"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)