Skip to content

WebAPI 自定义某类型的 JsonConverter

🏷️ WebAPI JSON

定义 Web Api 中返回 JSON 之后, 如果想自定义改变某种类型的序列化及反序列化格式该如何实现呢?

只需要通过继承 JsonConverter 抽象类, 并重写其方法即可实现。

下面是自定义日期(DateTime)类型的 Converter 类:

csharp
/// <summary>
/// 日期类型的 Json 转换器
/// </summary>
public class DateTimeConverter : JsonConverter
{
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The Newtonsoft.Json.JsonWriter to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime? dt = value as DateTime?;
        if (dt.HasValue)
        {
            writer.WriteValue(dt.Value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        else
        {
            writer.WriteValue(string.Empty);
        }
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The Newtonsoft.Json.JsonReader to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return Convert.ToDateTime(reader.Value);
    }

    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>true if this instance can convert the specified object type; otherwise, false.</returns>
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }
}

实现 Converter 之后要在 WebApiConfigRegister 方法中添加该 Converter:

cs
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Converter.DateTimeConverter()); //添加自定义的日期类型转换器