How to serialize DateTimeOffset as JSON in NancyFX?

六眼飞鱼酱① 提交于 2019-12-08 03:02:29

问题


I'm attempting to return some JSON from my Nancy application, using the default JSON serializer. I've got the following DTO class:

class Event
{
    public DateTimeOffset Timestamp { get; set; }
    public string Message { get; set; }
}

When I return it, as follows:

return Response.AsJson(
    new Event { Message = "Hello", Timestamp = DateTime.UtcNow });

...I get all of the DateTimeOffset properties returned, so it looks like this:

"Timestamp": {
    "DateTime":"\/Date(1372854863408+0100)\/",
    "UtcDateTime":"\/Date(1372858463408)\/",
    "LocalDateTime":"\/Date(1372858463408+0100)\/",
    "Date":"\/Date(1372806000000+0100)\/",
    "Day":3,
    "DayOfWeek":3

I was expecting "Timestamp":"\/Date(1372854863408+0100)\/", with none of the other stuff. This is the format that Nancy uses for DateTime values.

How do I configure Nancy to output DateTimeOffset values in the same style?


回答1:


I believe it's the built-in JsonSerializer which is responsible for this.

Any reason you can't use this approach?

return Response.AsJson(
    new Event { Message = "Hello", Timestamp = DateTime.UtcNow.ToString() });



回答2:


You can solve this problem without resorting to a custom serializer by adding a property to your model object that returns the DateTimeOffset.DateTime property. Then change your DateTimeOffset property to internal instead of public to make sure it won't be returned by the JSON serializer.

This approach also allows you to keep your standard JSON timestamp that you wanted as well as allowing you to keep the DateTimeOffset for server side use.

public class Event
{
    internal DateTimeOffset Timestamp { get; set; }
    public DateTime DateTimeOnly {
        get { return Timestamp.DateTime; }
    }
    public string Message { get; set; }
}

Raw JSON Result From Fiddler:

{"DateTime":"\/Date(1373309306039-0400)\/","Message":"Hello"}


来源:https://stackoverflow.com/questions/17449673/how-to-serialize-datetimeoffset-as-json-in-nancyfx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!