2

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?

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380

2 Answers2

2

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() });
jhovgaard
  • 560
  • 4
  • 18
  • 2
    Have you considered using Json.Net or ServiceStack with Nancy? They provide builtin handlers for DateTimeOffset. Or try writing something like https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Json/Converters/TimeSpanConverter.cs but for DateTimeOffset – Felipe Leusin Jul 04 '13 at 15:48
0

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"}
Chad Wilkin
  • 311
  • 1
  • 5
  • 11