c# - Serializing multiple DateTime properties in the same class using different formats for each one -
i have class 2 datetime properties. need serialize each of properties different format. how can it? tried:
jsonconvert.serializeobject(obj, formatting.none, new isodatetimeconverter {datetimeformat = "mm.dd.yyyy"});
this solution doesn't work me because applies date format properties. there way serialize each datetime property different format? maybe there attribute?
newtonsoft.json
has structure that's bit difficult understand, can use following custom converter want:
[testmethod] public void conversion() { var obj = new dualdate() { dateone = new datetime(2013, 07, 25), datetwo = new datetime(2013, 07, 25) }; assert.areequal("{\"dateone\":\"07.25.2013\",\"datetwo\":\"2013-07-25t00:00:00\"}", jsonconvert.serializeobject(obj, formatting.none, new dualdatejsonconverter())); } class dualdate { public datetime dateone { get; set; } public datetime datetwo { get; set; } } class dualdatejsonconverter : jsonconverter { public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { jobject result = new jobject(); dualdate dd = (dualdate)value; result.add("dateone", jtoken.fromobject(dd.dateone.tostring("mm.dd.yyyy"))); result.add("datetwo", jtoken.fromobject(dd.datetwo)); result.writeto(writer); } // other jsonconvertermethods public override bool canconvert(type objecttype) { return objecttype == typeof(dualdate); } public override bool canwrite { { return true; } } public override bool canread { { return false; } } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { throw new notimplementedexception(); } }
Comments
Post a Comment