【问题标题】:Add new record in json在json中添加新记录
【发布时间】: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); 才能使上述代码正常工作。

标签: c# json.net


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2015-03-07
    • 2022-01-06
    相关资源
    最近更新 更多