2

I have a C# model that, when serialized to JSON, should render the date property in JSON like: Date(123456790)

To achieve this I added the Attribute to the DateTime Property:

    [JsonConverter(typeof(JavaScriptDateTimeConverter))]
    public DateTime DateOfBirth { get; set; }

However when the model is serialized, the resulting JSON looks like this:

{
    "Member": {
        "FirstName": "firstname",
        "LastName": "lastname",
        "UserName": "username",
        "Password": "password",
        "FullName": "firstname lastname",
        "DateOfBirth": newDate(350546400000),
        "Gender": "male",
        "Email": "my@email.com"
    },
    "UserId": "b8a8fd7583b14d6a81bbaeb561aef765",
}

What I need it to look like is this:

{
    "Member": {
        "FirstName": "firstname",
        "LastName": "lastname",
        "UserName": "username",
        "Password": "password",
        "FullName": "firstname lastname",
        "DateOfBirth": "/Date(350546400000)/",
        "Gender": "male",
        "Email": "my@email.com"
    },
    "UserId": "b8a8fd7583b14d6a81bbaeb561aef765",
}

According to the documentation, the property to do this is DateFormatHandling, which should be MicrosoftDateFormat.

However I don't want to modify ALL conversions to this, just this model... so I attempted to create a custom serializer that would use that format:

public class CustomJavaScriptDateTimeConverter : JavaScriptDateTimeConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
        base.WriteJson(writer, value, serializer);
    }
}

and updated the attribute to match:

    [JsonConverter(typeof(CustomJavaScriptDateTimeConverter))]
    public DateTime DateOfBirth { get; set; }

but although the custom serializer is hit, and the property is changed, the output is still the original "new Date(350546400000)" instead of what I want.

anybody know what i'm doing wrong here?

SelAromDotNet
  • 4,715
  • 5
  • 37
  • 59

1 Answers1

3

Your CustomConverter can be like this

public class CustomJavaScriptDateTimeConverter : JavaScriptDateTimeConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var js = new JsonSerializer() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
        js.Serialize(writer, value);
    }
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • woohoo that was the one! thank you! may I ask how did you know this, is there a doc about how this works, I'd like to learn more, or was this just your expertise :) either way many thanks! – SelAromDotNet Aug 30 '17 at 18:23