Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...