i'm trying deserialize json
{ "type": "correction", "starttime": "2007-12-19t03:00:00.0000000-08:00", "endtime": "2007-12-23t23:00:00.0000000-08:00", "parameters": [ { "key": "something", "value": "1.8" }, { "key": "something2", "value": "0.10000000000000001" }, { "key": "something3", "value": "answer3" }, ], } into dto including public ireadonlydictionary<string, string> parameters { get; set; } along many other things.
i'm using newest newtonsoft deserializer, function
var responseobject = jsonconvert.deserializeobject<tresponse>(jsonresponse); but returns error
newtonsoft.json.jsonserializationexception : cannot deserialize current json array (e.g. [1,2,3]) type 'system.collections.generic.ireadonlydictionary`2[system.string,system.string]' because type requires json object (e.g. {"name":"value"}) deserialize correctly. is there tool use change json response different response such
"parameters": { "something": "1.8", "something2": "0.10000000000000001", "something3": "answer3", }, which works (since array removed).
p.s. i've used regex replace, since smallest json change cause fail, i've giving on approach.
thanks!
you can write custom jsonconverter
public class kvlisttodictconverter<t1,t2> : newtonsoft.json.jsonconverter { public override bool canconvert(type objecttype) { return typeof(dictionary<t1, t2>) == objecttype; } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { if (reader.tokentype == jsontoken.startarray) return serializer.deserialize<list<keyvaluepair<t1, t2>>>(reader).todictionary(x => x.key, x => x.value); else { var c = serializer.converters.first(); serializer.converters.clear(); //to avoid infinite recursion var dict = serializer.deserialize<dictionary<t1, t2>>(reader); serializer.converters.add(c); return dict; } } public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { throw new notimplementedexception(); } } and use in deserialization like
var json = jsonconvert.deserializeobject<yourobject>(json, new kvlisttodictconverter<string,string>()); this work both first json, , 1 want regex.
Comments
Post a Comment