0

Please note that this is not about time conversion, but about converting JSON/C# types

I am need serialize and deserialize an object with a property DateTimeOffset but her value need be in milliseconds format when serialized; when deserialize, convert it to DateTimeOffset again. I came to this point:

public class JsonDateTimeOffsetAndMillisecondsConverter: JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var t = long.Parse((string)reader.Value);
        return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // How to write in json the datetime property as milliseconds?        }
}

But I not know how to serialize in milliseconds now. Can someone help me?

GustavoAdolfo
  • 361
  • 1
  • 9
  • 23

1 Answers1

1

Using the method from this answer, we can obtain the corresponding millisecond Unix epoch:

var valueDto = (DateTimeOffset)(DateTime)value;
var milliseconds = (valueDto).ToUnixTimeMilliseconds();

You then simply have to write the value:

writer.WriteValue(milliseconds);

Combining it, we get:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var valueDto = (DateTimeOffset)(DateTime)value;
    var milliseconds = (valueDto).ToUnixTimeMilliseconds();
    writer.WriteValue(milliseconds);
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Thank you. Now I am in doubt whether the method will preserve the standard serialization of the other properties of the class. – GustavoAdolfo Jul 08 '19 at 14:46
  • 2
    The `CanConvert` method only allows this to consider `DateTime` properties. If you don't want to register it against all `DateTime` properties, don't add it to your `JsonSerializerSettings`. Instead, decorate the property you want this applied to with a `[JsonConverter(typeof(JsonDateTimeOffsetAndMillisecondsConverter))]` attribute. – ProgrammingLlama Jul 08 '19 at 23:49