Newtonsoft.json IsoDateTimeConverter and DateFormatHandling

我的梦境 提交于 2019-12-05 22:50:35
dbc

You actually have several different related questions. Let's break them down:

What happens when I add a converter for a type that is natively supported by Json.NET?

If you do that, your converter supersedes the native Json.NET functionality. For instance, you can replace its serialization of byte [] fields. Or you can change how it serializes and deserializes numbers: this slightly silly converter serializes integers by adding 1:

public class IntConverter : JsonConverter
{ 
    public override bool CanConvert(Type objectType) { return objectType == typeof(int); }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return (int)JValue.Load(reader) - 1;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(1 + (int)value);
    }
}

Why does Json.NET provide various DateTime converters as well as native support for multiple DateTime formats?

This is explained in the documentation Serializing Dates in JSON

DateTimes in JSON are hard.

The problem comes from the JSON spec itself: there is no literal syntax for dates in JSON. The spec has objects, arrays, strings, integers, and floats, but it defines no standard for what a date looks like.

The native support for dates handles some commonly encountered formats; if you have dates in some other format you can derive from DateTimeConverterBase. (For an example, see How to convert new Date(year, month, day) overload with JSON.Net.) Having done so, your converter will supersede the native conversion specified by DateFormatHandling.

Why does Json.NET have a class IsoDateTimeConverter that seems to duplicate the functionality of DateFormatHandling.IsoDateFormat?

This is a legacy class. From Serializing Dates in JSON

From Json.NET 4.5 and onwards dates are written using the ISO 8601 format by default, and using this converter is unnecessary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!