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": "[email protected]"
    },
    "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": "[email protected]"
    },
    "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?

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.