我想在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.
答案 0 :(得分:1)
您调用array
的变量不是基于上面json的数组。该数组位于features
属性中。您必须执行array.features.Add(jsonObject);
才能使上述代码生效。
像
var rootObject = JsonConvert.DeserializeObject<dynamic>(json);
dynamic feature = new JObject();
feature.type = "Feature";
feature.id = 3;
feature.name = sAddress;
dynamic geometry = new JObject();
geometry.type = "Point";
geometry.coordinates = new JArray(12, 13);
feature.geometry = geometry;
rootObject.features.Add(feature);