问题
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