C# 操作 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11047708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Manipulating JSON data
提问by Nebula
I have a 'simple' scenario: Read some JSON file, Filter or change some of the values and write the resulting json back without changing the original formatting.
我有一个“简单”的场景:读取一些 JSON 文件,过滤或更改一些值并将生成的 json 写回而不更改原始格式。
So for example to change this:
因此,例如要改变这一点:
{
"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
]
]
]
}
}
]
}
Into this:
进入这个:
{
"type": "FeatureCollection",
"crs": {
"type": "EPSG",
"properties": {
"code": 28992
}
},
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates":
[
149886.192,
374554.705
]
}
}
]
}
I've tried JSON.Net by newtonsoft among others but the only this I can find is:
我已经尝试过 newtonsoft 的 JSON.Net,但我唯一能找到的是:
- read into object
- write object to json
- 读入对象
- 将对象写入 json
But I'm missing the 'change the object' step. Any hints?
但我错过了“更改对象”步骤。任何提示?
Update
更新
Here's what I've tried so far:
这是我迄今为止尝试过的:
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";
}
But this only changes the value of the geoType variable. I'd expected to change the value insidethe geometry as well. I need a reference, not a copy! Is this possible?
但这只会改变 geoType 变量的值。我也希望改变几何内部的值。我需要参考,而不是副本!这可能吗?
Update
更新
I am currently off this project but I'd like to give my feedback to the answerers. Though I like the simplicity of Shahin, I like the more formal approach of L.B. a bit better. I personally don't like using string values as functional code, but that's just me. If I could accept both answers: I would. I guess Shahin wil have to make due with 'just' an upvote.
我目前不在这个项目中,但我想向回答者提供我的反馈。虽然我喜欢 Shahin 的简单,但我更喜欢 LB 更正式的方法。我个人不喜欢使用字符串值作为功能代码,但这只是我。如果我能接受这两个答案:我愿意。我想沙欣将不得不“只是”投赞成票。
采纳答案by L.B
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();
回答by Asif Mushtaq
Using
Json.netyou have to create the entities representing yourjsonDeserialize the
jsoninto those enties likeJson.Convert<FeatureCollection>(json)Change the entities
Convert it back to
json.
使用
Json.net您必须创建代表您的实体json将其反序列
json化为那些实体,例如Json.Convert<FeatureCollection>(json)更改实体
将其转换回
json.
回答by Shahin
If you don't want using any entity that representing your JSON, you can deserialize to Dictionary by using json.net and modify dictionary, then serialize it to JSON by using Json.net.
如果您不想使用任何代表您的 JSON 的实体,您可以使用 json.net 反序列化为 Dictionary 并修改字典,然后使用 Json.net 将其序列化为 JSON。
回答by Capt. Rochefort
I know this has already been answered but I thought I had a solution others might find interesting.
我知道这已经得到了回答,但我认为我有一个其他人可能会觉得有趣的解决方案。
I had a pretty large stringified JSON object that I received from a customer and needed to manipulate in C# and then return in string form back to the calling application.
我从客户那里收到了一个非常大的字符串化 JSON 对象,需要在 C# 中进行操作,然后以字符串形式返回给调用应用程序。
It didn't make sense to model every aspect of the object, many parts that I wasn't planning on manipulating were changing often and I couldn't be expected to update my application every time the caller modified portions of their JSON object I wasn't being asked to manipulate. So I tried this, it's a bit ugly but it worked well:
对对象的每一个方面进行建模都没有意义,我不打算操作的许多部分经常更改,并且每次调用者修改他们的 JSON 对象的部分时,我不能期望我更新我的应用程序'不被要求操纵。所以我尝试了这个,它有点难看,但效果很好:
- Create a class (
myClass) representing justthe section you want to manipulate. Using Newtonsoft, create a dynamic version of the stringified JSON object:
dynamic jsonObj = JsonConvert.DeserializeObject(stringifiedJsonObject);Build your replacement object using the class you created above (
myClass). Then serialize that object usingstring stringPartialJsonObj = JsonConvert.SerializeObject(myClass);Next, (and this is the trick) deserialize the object you just created. Now it's the same type as your source.
dynamic partialJsonObj = JsonConvert.Deserialize(stringPartialJsonObj);Imagine (for the sake of this demonstration) in the original Json object, I needed to modify the object in
obj.ConfigurationData.Configuration1.Data. This is how I'd do it:jsonObj.ConfigurationData.Configuration1.Data = partialJsonObj;Finally, I'd re-serialize the whole thing and send it back to the user:
return JsonConvert.SerializeObject(jsonObj);
- 创建一个仅
myClass代表要操作的部分的类 ( ) 。 使用 Newtonsoft,创建字符串化 JSON 对象的动态版本:
dynamic jsonObj = JsonConvert.DeserializeObject(stringifiedJsonObject);使用您在上面创建的类 (
myClass)构建您的替换对象。然后使用序列化该对象string stringPartialJsonObj = JsonConvert.SerializeObject(myClass);接下来,(这就是诀窍)反序列化您刚刚创建的对象。现在它与您的源类型相同。
dynamic partialJsonObj = JsonConvert.Deserialize(stringPartialJsonObj);想象一下(为了这个演示)在原始 Json 对象中,我需要修改
obj.ConfigurationData.Configuration1.Data. 这就是我要做的:jsonObj.ConfigurationData.Configuration1.Data = partialJsonObj;最后,我将重新序列化整个内容并将其发送回用户:
return JsonConvert.SerializeObject(jsonObj);
It's a bit clunky, but it works. Story of my life :-)
它有点笨重,但它有效。我的生活故事:-)

