Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c# - JSON.NET Serialize DateTime.MinValue as null

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".

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Console output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...