我有一个像这样的 JSON 值
{"$id":"649271776","$type":"outdoorgame","Overs":50,"Balls":6,"TeamName":"TestTeam"}
我写了一个这样的 C# 代码来将 Overs 的值从 50 更改为 10
var jsonString = sSession.GameState; //this is the value {"$id":"649271776","$type":"outdoorgame","Overs":50,"Balls":6,"TeamName":"TestTeam"}
dynamic jsonObject =
Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
jsonObject.Overs = 10;
var modifiedJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
此代码将 Overs 的值从 50 更改为 10。我在使用上述代码时遇到的问题 modifiedJsonString 缺少这两个值
"$id":"649271776","$type":"outdoorgame"
将输出作为 {Overs":10,"Balls":6,"TeamName":"TestTeam"}
我想要 $id
和 $在 modifiedJsonString 中输入
。
我想要这样的 modifiedJsonString {"$id":"649271776","$type":"outdoorgame","Overs":10,"Balls":6,"TeamName":"TestTeam"}
谁能告诉我如何解决这个问题
最佳答案
问题是 $id
和 $type
不是有效的标识符,不能作为由 JSON 序列化程序构建的返回动态对象的成员出现。正如在 gldraphael 的回答中,解决方案是创建自己的具体类来保存反序列化的对象;对于名称以 $
开头的属性,您需要使用 JsonPropertyAttribute
来重新映射名称:
public class GameState
{
[JsonProperty("$id")] public string ID { get; set; }
[JsonProperty("$type")] public string Type { get; set; }
int Overs { get; set; }
int Balls { get; set; }
public string TeamName { get; set; }
}
进一步,Json.NET treats $type
as a special property name这会干扰对象的正确反序列化。要解决这个问题,我们必须使用 MetadataPropertyHandling.Ignore
序列化程序设置。
因此您可以像这样反序列化、修改和重新序列化:
string jsonString = "{\"$id\":\"649271776\",\"$type\":\"outdoorgame\",\"Overs\":50,\"Balls\":6,\"TeamName\":\"TestTeam\"}";
JsonSerializerSettings settings = new JsonSerializerSettings() { MetadataPropertyHandling = MetadataPropertyHandling.Ignore };
GameState jsonObject = JsonConvert.DeserializeObject<GameState>(jsonString, settings);
jsonObject.Overs = 10;
var modifiedJsonString = JsonConvert.SerializeObject(jsonObject);
关于c# - JSON 变化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609308/