gpt4 book ai didi

C# 操作 JSON 数据

转载 作者:可可西里 更新时间:2023-11-01 03:09:50 24 4
gpt4 key购买 nike

我有一个“简单”的场景:读取一些 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
]
]
]
}
}
]
}

进入这个:

{
"type": "FeatureCollection",
"crs": {
"type": "EPSG",
"properties": {
"code": 28992
}
},
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates":
[
149886.192,
374554.705
]
}
}
]
}

我试过 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";
}

但这只会改变 geoType 变量的值。我还希望更改内部 几何体的值。我需要引用,而不是副本!这可能吗?

更新

我目前不在这个项目中,但我想向回答者提供反馈。虽然我喜欢 Shahin 的简单,但我更喜欢 L.B. 更正式的方法。好一点。我个人不喜欢将字符串值用作功能代码,但我就是这样。如果我能接受这两个答案:我愿意。我猜 Shahin 将不得不“只”投赞成票。

最佳答案

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();

关于C# 操作 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com