手动创建JSON
c#
我有一个 JSON,例如可以是这样的:
{
"value":[
{
"Name":"Nik",
"Age":"17",
"Country":"Germany",
},
{
"Name":"Tom",
"Age":"20",
"Country":"Russia",
},
{
"Name":"Sila",
"Age":"12",
"Country":"Switzerland",
}
]
}
“姓名”和“年龄”等属性的键是动态的,可以变化。JSON 也可能如下所示:
{
"value":[
{
"Prename":"Nik",
"Age":"17",
"Country":"Germany"
"Car":"Merc"
},
{
"Prename":"Nik",
"Age":"20",
"Country":"Russia"
"Car":"BMW"
},
{
"Prename":"Nik",
"Age":"12",
"Country":"Switzerland",
"Car":"Audi"
}
]
}
重要的是结构,这就是我想用Newtonsoft.Json.
这是我目前的尝试:
var jArray = new JArray();
jArray.Add("Name");
jArray.Add("Nikola");
jArray.Add("Age");
jArray.Add("17");
jArray.Add("Country");
jArray.Add("Germany");
JObject o = new JObject();
o["Value"] = jArray;
string json = o.ToString();
结果:
{
"Value": [
"Name",
"Nikola",
"Age",
"17",
"Country",
"Germany"
]
}
我试图用来自 newtonsoft 网站的这个例子来解决它,但正如你所看到的,它的解释真的很糟糕。
回答
您需要JObject像这样添加到数组中。我想你必须添加任何你想要的条件属性(或其他嵌套对象)
var jArray = new JArray();
var nik = new JObject();
nik["Name"] = "nik";
nik["Age"] = "17";
nik["Country"] ="Germany";
jArray.Add(nik);
JObject o = new JObject();
o["Value"] = jArray;
string json = o.ToString();
根据动态内容的确切性质,您可以使用初始化程序代码,例如
var jArray = new JArray
{
new JObject {["Name"] = "nik", ["Age"] = "17", ["Country"] = "Germany"},
new JObject {["Name"] = "bob", ["Age"] = "32", ["Country"] = "New Zealand"}
};
var o = new JObject {["Value"] = jArray};