Search code examples
c#jsonservicestackservicestack-text

ServiceStack Deserialize int (unix timestamp in ms) to DateTime


Here is a snippet of my current class: As you can see I'm deserializing to a long and then once it's done it calls the OnDeserialized method to finish up. Does ServiceStack have a better way to do that? Possibly a more direct way to so I won't need that extra method?

[DataMember(Name = "t")]
public long Timestamp { get; set; }
public DateTime Timestamp { get; set; }

[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
    Timestamp = DateTimeOffset.FromUnixTimeMilliseconds(TimestampLong).LocalDateTime;
}

UPDATE: I tried both of the methods you suggested but neither worked for me. Here's more code so hopefully you can identify my mistake:

MyClass

[DataContract]
public class MyClass
{
    //... (other members working fine)
    
    [DataMember(Name = "t")]
    public DateTime Timestamp { get; set; }
}

Deserializing (Unit Test)

var message = "[{...(other members working fine)...\"t\":1612446479354}]";
using var config = JsConfig.With(new Config {DateHandler = DateHandler.UnixTime});
//var myClass = message.FromJson<MyClass[]>();
var myClass = JsonSerializer.DeserializeFromString<MyClass[]>(message);

Assert.IsTrue(ticks[0].Timestamp == DateTimeOffset.FromUnixTimeMilliseconds(1612446479354).LocalDateTime);

Solution

  • Yes you can specify a scoped configuration to tell the serializer the Date Times are sent as unix times, e.g:

    using var config = JsConfig.With(new Config { DateHandler = DateHandler.UnixTimeMs });
    var dto = JsonSerializer.DeserializeFromString<MyType1>(json);
    

    If all DateTime's are sent as Unix Times you can specify a global configuration on Startup with:

    JsConfig.Init(new Config {
        DateHandler = DateHandler.UnixTimeMs
    });