使用JSON.NET将C#DateTime序列化为JSON日期

时间:2017-08-30 18:02:01

标签: c# json datetime serialization

我有一个C#模型,当序列化为JSON时,应该在JSON中呈现日期属性,如:Date(123456790)

为实现这一点,我将属性添加到DateTime属性:

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

但是,当序列化模型时,生成的JSON如下所示:

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

我需要它看起来像这样:

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

根据documentation,执行此操作的属性是DateFormatHandling,它应该是MicrosoftDateFormat。

但是我不想修改所有转换,仅此模型...所以我尝试创建一个使用该格式的自定义序列化器:

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

并更新了要匹配的属性:

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

但是虽然命中了自定义序列化程序,并且属性已更改,但输出仍然是原始的“新日期(350546400000)”而不是我想要的。

有人知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:3)

您的CustomConverter可以是这样的

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);
    }
}