序列化为JSON,尽管指定了NullValueHandling,但使用Json.NET和Web API省略了可空日期 [英] Serializing to JSON, Nullable Date gets omitted using Json.NET and Web API despite specifying NullValueHandling

查看:839
本文介绍了序列化为JSON,尽管指定了NullValueHandling,但使用Json.NET和Web API省略了可空日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using Newtonsoft.Json;

namespace FAL.WebAPI2012.Controllers
{
    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; }
    }

    public class TestNullsController : ApiController
    {
        // GET api/<controller>
        public Person Get()
        {
            Person myPerson = new Person() { 
                Dob = null, FirstName = "Adrian", Id=1, LastName="Bobby"
            };

            return myPerson;
        }
    }
}

如您所见,我的Dob字段设置为null,但结果如下

As you can see, my Dob field is set to null but the result is the following

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

Dob没有序列化为null,我需要将其设置为空!

and Dob is not serialized to null which I need it to be!

(我已经测试过JsonProperty设置了其他属性,例如name,它完美地改变了JSON输出.我只是无法将nullable属性进行序列化. 另外,我已经测试了Json.Net(请参阅下面的答案),所以我的想法是Web api安装程序将覆盖某个地方的东西,很高兴知道在哪里.

(I have tested that JsonProperty is setting other attributes like name and it changes the JSON output perfectly. I just can't get the nullable property to be serialized. Also, I have tested Json.Net (see answer below), so my thinking is that web api setup is overriding something somewhere, would be nice to know where).

推荐答案

我收到了来自Microsoft的web.api成员的答复.

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

'您将很高兴知道自RC以来此问题已得到解决:

'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 =新的JsonSerializerSettings(){NullValueHandling = NullValueHandling.Include};

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

希望有帮助'

因此,所有更新均适用.

So, all works with that update.

这篇关于序列化为JSON,尽管指定了NullValueHandling,但使用Json.NET和Web API省略了可空日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆