c# - Insert custom data to JSON serialized from DataModel -
i have data model class i'm serializing json in order able post serialized json web service. data model this:
using newtonsoft.json; namespace webcrawler.models { [jsonobject(memberserialization.optin)] public class linkdataviewmodel { [jsonproperty] public string title { get; set; } ..... [jsonproperty] public string customerid { get; set; } } }
how should change data model class serialized json that:
{"postpropertyrequest": {serializeddatamodel}}
you can write custom json in way (make class derived jsonconverter , override 3 methods)
using newtonsoft.json; namespace webcrawler.models { [jsonobject(memberserialization.optin)] public class linkdataviewmodel : jsonconverter { [jsonproperty] public string title { get; set; } ..... [jsonproperty] public string customerid { get; set; } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { throw new notimplementedexception(); } public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { if (value == null) { serializer.serialize(writer, null); return; } var properties = value.gettype().getproperties(); writer.writestartobject(); //your custom property writer.writepropertyname("postpropertyrequest"); writer.writestartobject(); foreach (var property in properties) { // write property name writer.writepropertyname(property.name); serializer.serialize(writer, property.getvalue(value, null)); } writer.writeendobject(); writer.writeendobject(); } } }
refer nice article documentation
Comments
Post a Comment