asp.net - Web Api not converting json empty strings values to null -


example json: {"field1":"","field2":null}.

in mvc, field1 converted null default. tried [displayformat(convertemptystringtonull = true)] attribute, (which should default anyway) , did not make difference.

i'm using web api 2.1

any ideas?

first empty string not null, , json.net underlying json implementation should not auto conversions.

you can add following custom converter deal that

public class emptytonullconverter : jsonconverter {     private jsonserializer _stringserializer = new jsonserializer();      public override bool canconvert(type objecttype)     {         return objecttype == typeof(string);     }      public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         string value = _stringserializer.deserialize<string>(reader);          if (string.isnullorempty(value))         {             value = null;         }          return value;     }      public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         _stringserializer.serialize(writer, value);     } } 

and use in class decorate properties want convert with

[jsonconverter(typeof(emptytonullconverter))] public string familyname { get; set; } 

you can add converter config.formatters.jsonformatter.serializersettings.converters , apply strings instead. note required private member _stringserializer otherwise stackoverflow. member not required if decorate string property directly.

in webapiconfig.cs add following line:

config.formatters.jsonformatter.serializersettings.converters.add(new emptytonullconverter()); 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -