【发布时间】:2017-12-31 14:21:49
【问题描述】:
我想在 json 集合中添加一条新记录:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"name": "Location1",
"geometry": {
"type": "Point",
"coordinates": [
150.74379,
-30.280119
]
}
},
{
"type": "Feature",
"id": 2,
"name": "Location2",
"geometry": {
"type": "Point",
"coordinates": [
148.387392,
-23.781484
]
}
}]
}
我想找到创建这样一个对象并插入它的最佳方法。到目前为止,我添加了下面的代码,这会引发错误
无法将 Newtonsoft.Json.Linq.JObject 添加到 Newtonsoft.Json.Linq.JObject。
当我想将新对象添加到数组中时
var array = JsonConvert.DeserializeObject<dynamic>(json);
dynamic jsonObject = new JObject(); // needs using Newtonsoft.Json.Linq;
jsonObject.type = "feature";
jsonObject.id = 3;
jsonObject.name = sAddress;
jsonObject.type = "Point";
jsonObject.coordinates = "12, 13";
array.Add(jsonObject); // error Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.
【问题讨论】:
-
基于 json 创建强类型对象。反序列化 json。添加新对象。重新序列化。完成。
-
你调用
array的变量不是基于上面json的数组。该数组位于 features 属性中。您必须执行array.features.Add(jsonObject);才能使上述代码正常工作。