Serializing to JSON, Nullable Date gets omitted using Json.NET and Web API despite specifying NullValueHandling

纵饮孤独 提交于 2019-12-05 15:54:11

It would appear that the problem lies somewhere else. I've done the following in a console application:

using System;
using System.IO;
using Newtonsoft.Json;

namespace JsonNetNullablePropertyTest
{
    class Program
    {
        static void Main()
        {
            var myPerson = new Person {
                Dob = null,
                FirstName = "Adrian",
                Id = 1,
                LastName = "Bobby"
            };

            using (var textWriter = new StringWriter())
            using (var writer = new JsonTextWriter(textWriter))
            {
                // Create the serializer.
                var serializer = new JsonSerializer();

                // Serialize.
                serializer.Serialize(writer, myPerson);

                // Write the output.
                Console.WriteLine(textWriter);
            }
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include,
            NullValueHandling = NullValueHandling.Include)]
        public DateTime? Dob { get; set; }
    }
}

And the output is:

{"Id":1,"FirstName":"Adrian","LastName":"Bobby","Dob":null}

As expected.

It would seem that the problem lies in how you are actually calling the JsonSerializer to serialize the Person instance.

I received this reply from a member of the web.api folk at Microsoft.

'You'll be glad to know this has been fixed since RC:

http://aspnetwebstack.codeplex.com/workitem/243

You can either upgrade to a newer package, or you can override our settings like this:

JsonFormatter.SerializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include };

Hope that helps'

So, all works with that update.

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