json - Serializing .MinValue of value types (C#) in ASP.NET Web API 2 to null -
i serialize .minvalue of value types (c#) in asp.net web api 2 null when passing client. when client sends value null .minvalue value types on server.
i using json.net json serialization , deserialization. further need same uri parameters , maybe formdata. following types need: short, int, long, float, double, decimal, datetime
things tried:
- one solution work nullable types. on server prefer work not nullable types because business logic layer working value types , in data access layer converted dbnull if .minvalue.
- i wrote jsonconverter datetime (derived isodatetimeconverter) handle datetime.minvalue null , vice versa. works fine, not sure how numbers because don't have jsonconverter implementations in json.net or can't find them.
- for uri-parameters try implementation of imodelbinder
is there built in way in json.net handle needs have not found?
how can overwrite number-serialization (int, decimal, ..) in json.net?
any other idea satisfy needs...
you use custom converter this:
public class valuetypeconverter : jsonconverter { private static list<type> supportedtypes = new list<type> { typeof(short), typeof(int), typeof(long), typeof(float), typeof(double), typeof(decimal), typeof(datetime) }; private static dictionary<type, object> minvalues; static valuetypeconverter() { minvalues = new dictionary<type, object>(); foreach (type type in supportedtypes) { minvalues.add(type, getminvalue(type)); } } public override object readjson( jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { object value = reader.value; value = value ?? minvalues[objecttype]; value = convert.changetype(value, objecttype); return value; } public override bool canconvert(type objecttype) { return minvalues.containskey(objecttype); } public override void writejson( jsonwriter writer, object value, jsonserializer serializer) { object minvalue = minvalues[value.gettype()]; if (object.equals(value, minvalue)) { value = null; } writer.writevalue(value); } private static object getminvalue(type objecttype) { fieldinfo minvaluefieldinfo = objecttype.getfield("minvalue"); return minvaluefieldinfo.getvalue(null); } }
usage:
var settings = new jsonserializersettings { converters = new[] { new valuetypeconverter() } }; string json = jsonconvert.serializeobject(obj, settings);
example: https://dotnetfiddle.net/wphjr5
Comments
Post a Comment