使用 Json.NET 使用新的部分 JSON 数据修改现有对象
本文关键字:数据 JSON 修改 对象 NET Json 使用 | 更新日期: 2023-09-27 18:34:21
考虑以下示例程序
var calendar = new Calendar
{
Id = 42,
CoffeeProvider = "Espresso2000",
Meetings = new[]
{
new Meeting
{
Location = "Room1",
From = DateTimeOffset.Parse("2014-01-01T00:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T01:00:00Z")
},
new Meeting
{
Location = "Room2",
From = DateTimeOffset.Parse("2014-01-01T02:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T03:00:00Z")
},
}
};
var patch = @"{
'coffeeprovider': null,
'meetings': [
{
'location': 'Room3',
'from': '2014-01-01T04:00:00Z',
'to': '2014-01-01T05:00:00Z'
}
]
}";
var patchedCalendar = Patch(calendar, patch);
Patch()
方法的结果应等于 calendar
,除非更改了 patch
。这意味着; Id
将保持不变,CoffeeProvider
将设置为 null
,并且Meetings
将包含位于 Room3 中的单个项目。
如何
Patch()
创建一个适用于可反序列化的任何对象(不仅仅是示例日历对象(Json.NET?如果(1(这不可行,会有什么限制可以使其可行,如何实施?
您希望JsonSerializer.Populate()
或其静态包装器方法JsonConvert.PopulateObject()
:
将 JSON 值填充到目标对象上。
例如,这里它正在更新Calendar
类的实例:
public static class TestPopulate
{
public static void Test()
{
var calendar = new Calendar
{
Id = 42,
CoffeeProvider = "Espresso2000",
Meetings = new[]
{
new Meeting
{
Location = "Room1",
From = DateTimeOffset.Parse("2014-01-01T00:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T01:00:00Z")
},
new Meeting
{
Location = "Room2",
From = DateTimeOffset.Parse("2014-01-01T02:00:00Z"),
To = DateTimeOffset.Parse("2014-01-01T03:00:00Z")
},
}
};
var patch = @"{
'coffeeprovider': null,
'meetings': [
{
'location': 'Room3',
'from': '2014-01-01T04:00:00Z',
'to': '2014-01-01T05:00:00Z'
}
]
}";
Patch(calendar, patch);
Debug.WriteLine(JsonConvert.SerializeObject(calendar, Formatting.Indented));
}
public static void Patch<T>(T obj, string patch)
{
var serializer = new JsonSerializer();
using (var reader = new StringReader(patch))
{
serializer.Populate(reader, obj);
}
}
}
生成的调试输出为:
{
"id": 42,
"coffeeprovider": null,
"meetings": [
{
"location": "Room3",
"from": "2014-01-01T04:00:00+00:00",
"to": "2014-01-01T05:00:00+00:00"
}
]
}
更新
如果要先复制,可以执行以下操作:
public static T CopyPatch<T>(T obj, string patch)
{
var serializer = new JsonSerializer();
var json = JsonConvert.SerializeObject(obj);
var copy = JsonConvert.DeserializeObject<T>(json);
using (var reader = new StringReader(patch))
{
serializer.Populate(reader, copy);
}
return copy;
}