JSON.NET将DateTime.MinValue序列化为null [英] JSON.NET Serialize DateTime.MinValue as null

查看:93
本文介绍了JSON.NET将DateTime.MinValue序列化为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将由我的Web API返回的设置为DateTime.MinValueDateTime字段序列化为NULL而不是"0001-01-01T00:00:00".

I'd like DateTime fields that are set to DateTime.MinValue returned by my Web API to be serialized to NULL instead of "0001-01-01T00:00:00".

我知道有一种方法可以使JSON.NET忽略设置为默认值的字段,但是我更希望JSON.NET专门序列化DateTime MinValue / "0001-01-01T00:00:00" as null.

I understand there's a way to get JSON.NET to omit fields that are set to default values, but I would prefer JSON.NET to specifically serialize DateTime MinValue / "0001-01-01T00:00:00" as null.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

创建一个自定义转换器,将DateTime.MinValue序列化为null,并(如果需要)将null反序列化为DateTime.MinValue:

Create a custom converter which serializes DateTime.MinValue into null, and (if required) deserializes null into DateTime.MinValue:

public class MinDateTimeConverter : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value == null)
            return DateTime.MinValue;

        return (DateTime)reader.Value;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime dateTimeValue = (DateTime)value;
        if (dateTimeValue == DateTime.MinValue)
        {
            writer.WriteNull();
            return;
        }

        writer.WriteValue(value);
    }
}

然后可以使用属性将转换器添加到数据类中,如本示例所示:

You can then use attributes to add the converter to your data class, as shown in this example:

public class Example
{
    [JsonConverter(typeof(MinDateTimeConverter))]
    public DateTime ValueOne { get; set; }

    [JsonConverter(typeof(MinDateTimeConverter))]
    public DateTime ValueTwo { get; set; }
}

public static void Main(string[] args)
{
    Example data = new Example();
    data.ValueOne = DateTime.MinValue;
    data.ValueTwo = DateTime.Now;

    JsonSerializer serializer = new JsonSerializer();

    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, data);
        Console.Write(writer.ToString());
    }

    Console.ReadKey();
}

控制台输出:

{"ValueOne":null,"ValueTwo":"2016-10-26T09:54:48.497463+01:00"}

这篇关于JSON.NET将DateTime.MinValue序列化为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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