0

I have an external API that sends 0 in fields where semantically it means lack of value. It's a timestamp. I serialize this property as DateTime but I don't want users to have unix epoch in this field when semantically it should be null.

So I tried to write a custom converter and serialize the property into DateTime? writing null value instead of converting 0 to DateTime.

But when I try to serialize it back into json Newtonsoft doesn't even call my converter if I pass null in the property.

The property is marked with these attributes:

  • [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
  • [JsonConverter(typeof(CustomUnixDateTimeConverter ))]

My custom converter:

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

internal class CustomUnixDateTimeConverter : UnixDateTimeConverter
{
    public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var nonNullable = Nullable.GetUnderlyingType(objectType) is null;

        return reader.TokenType == JsonToken.Integer && reader.Value is 0L
            ? nonNullable ? default : null
            : base.ReadJson(reader, objectType, existingValue, serializer);
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value is null || value.Equals(default(DateTime)))
        {
            writer.WriteValue(0);
        }
        else
        {
            base.WriteJson(writer, value, serializer);
        }
    }
}

What do I do wrong? Or is there a way to tell Newtonsoft to pass null values to my converter instead of handling null itself?

  • 1
    Short answer - no, there is not - `null` is special json token and Newtonsoft.Json [handles it](https://github.com/JamesNK/Newtonsoft.Json/blob/f7e7bd05d9280f17993500085202ff4ea150564a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs#L156) without any easy way to override this behaviour. – Guru Stron Nov 05 '21 at 22:19

0 Answers0