ServiceStack 反序列化 int (unix timestamp in ms) to DateTime

ServiceStack Deserialize int (unix timestamp in ms) to DateTime

这是我当前 class 的片段:如您所见,我正在反序列化为 long,然后一旦完成,它就会调用 OnDeserialized 方法来完成。 ServiceStack 有更好的方法吗?可能是更直接的方法,所以我不需要那个额外的方法?

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

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

更新: 我尝试了您建议的两种方法,但都不适合我。这里有更多代码,希望您能找出我的错误:

MyClass

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

反序列化(单元测试)

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

是的,您可以指定范围配置来告诉序列化程序日期时间作为 unix 时间发送,例如:

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

如果所有 DateTime 都作为 Unix 时间发送,您可以在启动时指定一个全局配置:

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