c# - Modify existing object with new partial JSON data using Json.NET -
consider below example program
var calendar = new calendar { id = 42, coffeeprovider = "espresso2000", meetings = new[] { new meeting { location = "room1", = datetimeoffset.parse("2014-01-01t00:00:00z"), = datetimeoffset.parse("2014-01-01t01:00:00z") }, new meeting { location = "room2", = datetimeoffset.parse("2014-01-01t02:00:00z"), = 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);
the result of patch()
method should equal calendar
except changed patch
. means; id
unchanged, coffeeprovider
set null
, meetings
contain single item located in room3.
how 1 create general
patch()
method work object (not example calendar object) deserializable json.net?if (1) not feasible, restrictions make feasible , how implemented?
you want jsonserializer.populate()
or static wrapper method jsonconvert.populateobject()
:
populates json values onto target object.
for instance, here updating instance of calendar
class:
public static class testpopulate { public static void test() { var calendar = new calendar { id = 42, coffeeprovider = "espresso2000", meetings = new[] { new meeting { location = "room1", = datetimeoffset.parse("2014-01-01t00:00:00z"), = datetimeoffset.parse("2014-01-01t01:00:00z") }, new meeting { location = "room2", = datetimeoffset.parse("2014-01-01t02:00:00z"), = 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); } } }
and debug output produced is:
{ "id": 42, "coffeeprovider": null, "meetings": [ { "location": "room3", "from": "2014-01-01t04:00:00+00:00", "to": "2014-01-01t05:00:00+00:00" } ] }
update
if want copy first, do:
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; }
Comments
Post a Comment