Wednesday 15 May 2013

c# - How to serialize an object to a JSON string property instead of an object using Json.Net -



c# - How to serialize an object to a JSON string property instead of an object using Json.Net -

i have next class structure. trying accomplish instead of bar serialized object in json, serialize string inner property name value , ignore id property. , don't have scenario need deserialize it, have load bar objects database other properties , internal manipulation not utilize transport.

class foo { [jsonproperty("bar")] public bar bar { get; set; } } class bar { [jsonignore] public guid id { get; set; } [jsonproperty] public string name { get; set; } }

expected json:

{ bar: "test" }

use custom jsonconverter , can command conversion output whatever want.

something like:

public class barconverter : jsonconverter { public override bool canconvert(type objecttype) { homecoming objecttype == typeof(bar); } public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { var bar = value bar; serializer.serialize(writer, bar.name); } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { // note: if need read to, you'll need implement here // otherwise throw notimplementexception , override `canread` homecoming false throw new notimplementedexception(); } }

then can either decorate property or bar class (depending on whether want bar serialized this, or property) jsonconverterattribute:

[jsonconverter(typeof(barconverter))] public bar bar { get; set; }

or:

[jsonconverter(typeof(barconverter))] public class bar

another "quick , dirty" way have shadow property serialized:

public class foo { [jsonproperty("bar")] // serialized "bar" public string barname { { homecoming bar.name; } } [jsonignore] // won't serialized public bar bar { get; set; } }

note if want able read you'd need provide setter , figure out how convert string name instance of bar. that's quick , dirty solution gets little unpleasant because don't have easy way restrict setting barname during deserialization.

c# json json.net

No comments:

Post a Comment