C# class, JSON serialization into single string -
say, have data structure in c# these:
[datacontract] public class myinner { [datamember] public string propertyone { get; set; } [datamember] public string propertytwo { get; set; } } [datacontract] public class myouter { [datamember] public string propertyone { get; set; } [datamember] public myinner propertytwo { get; set; } }
is possible serialize myouter object this:
{"propertyone": "p1", "propertytwo": "property 1 value;property 2 value"}
rather this:
{"propertyone": "p1", "propertytwo": { "propertyone" : "property 1 value", "propertytwo": "property 2 value" }}
i mean, able serialize object string property... there way it?
thanks, dario
you don't serializer using, following work both json.net , datacontractjsonserializer
.
what can add proxy property outer class, private or public prefer, returning inner class string. mark original property [ignoredatamember]
, proxy property [datamember(name="propertytwo")]
along these lines:
[datacontract] public class myinner { public static string converttostring(myinner myinner) { if (myinner == null) return null; return myinner.tostring(); } public static myinner convertfromstring(string value) { if (value == null) return null; var firstindex = value.indexof(';'); if (firstindex < 0) return new myinner { propertyone = value, propertytwo = string.empty }; else return new myinner { propertyone = value.substring(0, firstindex), propertytwo = value.substring(firstindex + 1, value.length - firstindex - 1) }; } [datamember] public string propertyone { get; set; } [datamember] public string propertytwo { get; set; } public override string tostring() { return string.format("{0};{1}", propertyone, propertytwo); } } [datacontract] public class myouter { [datamember] public string propertyone { get; set; } [ignoredatamember] public myinner propertytwo { get; set; } [datamember(name="propertytwo")] string propertytwotext { { return myinner.converttostring(propertytwo); } set { propertytwo = myinner.convertfromstring(value); } } }
note need decide myinner
property values containing ;
character. want escape them or throw exception them? consider creating typeconverter
inner class general use.
Comments
Post a Comment