C#操作JSON数据

Neb*_*ula 17 c# json json.net

我有一个"简单"的场景:读取一些JSON文件,过滤或更改一些值并将结果写回json,而不更改原始格式.

所以例如改变这个:

{
  "type": "FeatureCollection",
  "crs": {
    "type": "EPSG",
    "properties": {
      "code": 28992
    }
  },
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              149886.192,
              374554.705
            ],
            [
              149728.583,
              374473.112
            ],
            [
              149725.476,
              374478.215
            ]
          ]
        ]
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

进入:

{
  "type": "FeatureCollection",
  "crs": {
    "type": "EPSG",
    "properties": {
      "code": 28992
    }
  },
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": 
            [
              149886.192,
              374554.705
            ]
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过newtonsoft等JSON.Net,但我能找到的只有:

  • 读入对象
  • 将对象写入json

但我错过了"改变对象"的步骤.任何提示?

更新

这是我到目前为止所尝试的:

JToken contourManifest = JObject.Parse(input);

JToken features = contourManifest.SelectToken("features");

for (int i = 0; i < features.Count(); i++)
{
    JToken geometry = features[i].SelectToken("geometry");
    JToken geoType = geometry.SelectToken("type");
    JToken coordinates = geometry.SelectToken("coordinates");

    geoType = "Point";
}
Run Code Online (Sandbox Code Playgroud)

但这只会改变geoType变量的值.我希望也能改变几何体内的值.我需要一个参考,而不是副本!这可能吗?

更新

我目前不参与此项目,但我想向答复者提供反馈意见.虽然我喜欢Shahin的简单性,但我更喜欢LB更正式的方法.我个人不喜欢使用字符串值作为功能代码,但那只是我.如果我能接受这两个答案:我愿意.我猜Shahin将不得不用'just'一个upvote来做到.

L.B*_*L.B 14

dynamic contourManifest = JObject.Parse(input);
foreach (var feature in contourManifest.features)
{
    feature.geometry.Replace(
            JObject.FromObject(
                        new { 
                            type = "Point", 
                            coordinates = feature.geometry.coordinates[0][0] 
                        }));
}

var newJson = contourManifest.ToString();
Run Code Online (Sandbox Code Playgroud)