c# - JSON.NET: Serialize json string property into json object -
is possible tell json.net have string json data? e.g. have class this:
public class foo { public int id; public string rawdata; }
which use this:
var foo = new foo(); foo.id = 5; foo.rawdata = @"{""bar"":42}";
which want serialized this:
{"id":5,"rawdata":{"bar":42}}
basically have piece of unstructured variable-length data stored json already, need serialized object contain data part.
thanks.
edit: make sure understood properly, one-way serialization, i.e. don't need deserialize same object; other system shall process output. need content of rawdata part of json, not mere string.
you need converter that, here example:
public class rawjsonconverter : jsonconverter { public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { writer.writerawvalue(value.tostring()); } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { throw new notimplementedexception(); } public override bool canconvert(type objecttype) { return typeof(string).isassignablefrom(objecttype); } public override bool canread { { return false; } } }
then decorate class it:
public class foo { public int id; [jsonconverter(typeof(rawjsonconverter))] public string rawdata; }
then, when use:
var json = jsonconvert.serializeobject(foo, new jsonserializersettings()); console.writeline (json);
this output:
{"id":5,"rawdata":{"bar":42}}
hope helps
edit: have updated answer more efficient solution, previous 1 forced serialize deserialize, doesn't.
Comments
Post a Comment