序列化到JSON,可空日期被使用Json.NET和Web API,尽管指定NullValueHandling ommitted [英] Serializing to JSON, Nullable Date gets ommitted using Json.NET and Web API despite specifying NullValueHandling

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

问题描述

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;
        }
    }
}

正如你所看到的,我的多波字段设置为空,但结果是以下

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

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

多波不是序列为空,我需要它!

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

(我已经测试了 JsonProperty 是设置其他属性,如名称,它改变了JSON输出完美。我只是不能为null的属性被序列化。 另外,我已经测试Json.Net(见回答以下),所以我的想法是,网络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).

推荐答案

我收到了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.$c$cplex.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,可空日期被使用Json.NET和Web API,尽管指定NullValueHandling ommitted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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