Can't make MVC4 WebApi include null fields in JSON

主宰稳场 提交于 2019-12-05 06:26:18

This won't work:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;

But this does:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() 
{ 
NullValueHandling = Newtonsoft.Json.NullValueHandling.Include
};
Henry Vilinskiy

For some odd reason the Newtonsoft.Json.JsonFormatter ignore assigments to the propreties os SerializerSettings.

In order to make your setting work create new instance of .SerializerSettings as shown below:

config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
        {

            DefaultValueHandling =   Newtonsoft.Json.DefaultValueHandling.Include,
            NullValueHandling = Newtonsoft.Json.NullValueHandling.Include,

        };

I finally came across this http://forums.asp.net/t/1824580.aspx/1?Serializing+to+JSON+Nullable+Date+gets+ommitted+using+Json+NET+and+Web+API+despite+specifying+NullValueHandling which describes what I was experiencing as a bug in the beta that was fixed for the RTM.

Though I had installed VS2012 RTM, my project was still using all the nuget packages that the beta came with. So I nugetted (nugot?) updates for everything and all is now well (using #1 from my question). Though I'm feeling silly for having burned half a day.

When I saw this answer I was upset because I was already doing this and yet my problem still existed. My problem rooted back to the fact that my object implemented an interface that included a nullable type, so, I had a contract stating if you want to implement me you have to have one of these, and a serializer saying if one of those is null don't include it. BOOM!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!