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

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - 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);
question from:https://stackoverflow.com/questions/66048759/servicestack-deserialize-int-unix-timestamp-in-ms-to-datetime

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...