给定以下类别:
class Report {
public Report() {
this.Fields=new List<Field>();
}
[JsonProperty("fields")]
public IList<Field> Fields { get; private set; }
}
class Field {
[JsonProperty("identifier")]
public Guid Identfier { get;set; }
[JsonProperty("name")]
public string Name { get;set; }
}
Run Code Online (Sandbox Code Playgroud)
并设置以下测试方法:
var report = new Report();
report.Fields.Add(new Field { Identifier = new Guid("26a94eab-3d50-4330-8203-e7750abaa060"), Name = "Field 1" });
report.Fields.Add(new Field { Identifier = new Guid("852107db-b5d1-4344-9f71-7bd90b96fec0"), Name = "Field 2" });
var json = "{\"fields\":[{\"identifier\":\"852107db-b5d1-4344-9f71-7bd90b96fec0\",\"name\":\"name changed\"},{\"identifier\":\"ac424aff-22b5-4bf3-8232-031eb060f7c2\",\"name\":\"new field\"}]}";
JsonConvert.PopulateObject(json, report);
Assert.IsTrue(report.Fields.Count == 2, "The number of fields was incorrect.");
Run Code Online (Sandbox Code Playgroud)
如何使JSON.Net知道标识符为“ 852107db-b5d1-4344-9f71-7bd90b96fec0”的字段应应用于具有相同标识符的现有字段?
此外,是否有可能获取JSON.Net来删除给定JSON数组中不存在的项目,(特别是应删除标识符为“ 26a94eab-3d50-4330-8203-e7750abaa060”的字段,因为该字段在给定json数组。
如果可以手动编码或覆盖JSON分析列表的方式,那会更好,因为我可以编写代码说“这是您需要的商品”或“使用此新创建的商品”,或者只是“不要对这个项目不做任何事情,因为我已将其删除”。有人知道我可以做到这一点吗?
您可以使用该选项ObjectCreationHandling = ObjectCreationHandling.Replace。
您可以使用序列化程序设置对整个数据模型执行此操作,如Json.Net PopulateObject追加列表所示,而不是设置value:
var serializerSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};
JsonConvert.PopulateObject(json, report, serializerSettings);
Run Code Online (Sandbox Code Playgroud)
或者,JsonProperty如果不想通用地执行此操作,可以在已使用的属性上设置选项:
class Report
{
public Report()
{
this.Fields = new List<Field>();
}
[JsonProperty("fields", ObjectCreationHandling = ObjectCreationHandling.Replace)]
public IList<Field> Fields { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)