我有一个像这样的JObject:
JObject grid =
new JObject(
new JProperty("myprop", "value 1"),
new JProperty("name",
new JArray(
new JObject(
new JProperty("myprop2", "value 2")
)
)
)
)
没错。
但是,我有一个想要迭代的对象,并将它们添加到我的JObject中,但是如何做到这一点?
喜欢这个? (我知道这是无效的)
JObject grid =
new JObject(
new JProperty("myprop", "value 1"),
new JProperty("name",
new JArray(
new JObject(
new JProperty("myprop2", "value 2"),
foreach(var value in myObject) {
new JObject(
new JProperty(value.Name, value.Value)
)
}
)
)
)
)
我该怎么做?
答案 0 :(得分:1)
如果您事先知道您的数组项目,为什么不先创建它们?
var myprop2Items = new List<JObject>();
foreach(var value in myObject) {
myprop2Items.Add(new JObject(
new JProperty(value.Name, value.Value)
));
}
JObject grid =
new JObject(
new JProperty("myprop", "value 1"),
new JProperty("name",
new JArray(
new JObject(
new JProperty("myprop2", "value 2"),
myprop2Items
)
)
)
)
)
答案 1 :(得分:1)
您还可以向现有JObject添加属性:
var obj = new JObject();
Console.WriteLine(obj.ToString()); // {}
obj.Add("key", "value");
Console.WriteLine(obj.ToString()); // {"key": "value"}