[英]Json.NET - Add JObject to JArray
I have a very simple piece of code that I just cannot work out. 我有一段非常简单的代码,我无法解决。
JObject obj = new JObject { "Name", "John" };
JArray array = new JArray();
array.Add(obj);
// throws "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject"
I have tried many different things to add a JObject
to a JArray
. 我尝试了很多不同的方法,将JObject
添加到JArray
。 What am I doing wrong? 我究竟做错了什么?
Your problem is not the adding part. 您的问题不是增加的部分。
Your problem is the initialization of your JOject
. 您的问题是JOject
的初始化。
Try this. 尝试这个。
JObject obj = new JObject();
obj.Add("Name", "John");
Jarray array = new JArray();
array.Add(obj);
Another way to fix the problem cl0ud pointed out is to instantiate as such: 解决cl0ud指出的问题的另一种方法是这样实例化:
JObject obj = new JObject {
{ "Name", pRecord.getName() }
};
JArray array = new JArray();
array.Add(obj);
Note those extra curly braces 注意那些多余的花括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.