Web API - JsonConverter - 自定义属性

Web API - JsonConverter - Custom Attribute

我们有一个 Web api 项目,为了将日期时间转换为日期,反之亦然,我们使用从 JsonConverter 扩展的 DateTimeconverter。 我们以所有必需的 DateTime 属性的属性形式使用它(如下所示):

[JsonConverter(typeof(CustomDateConverter))]

CustomDateConverter 如下:

public class CustomDateConverter: JsonConverter
{
    private string[] formats = new string[] { "yyyy-MM-dd", "MM/dd/yy", "MM/dd/yyyy", "dd-MMM-yy" };

    public CustomDateConverter(params string[] dateFormats)
    {
        this.formats = dateFormats;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // custom code
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // custom code
    }
}

我的问题是如何在使用属性时定义自定义构造函数?

您可以使用 [JsonConverterAttribute(Type,Object[])] attribute constructor to pass arguments to your CustomDateConverter when it is constructed by Json.NET. This constructor automatically sets the ConverterParameters 属性:

public class RootObject
{
    [JsonConverter(typeof(CustomDateConverter), new object [] { new string [] { "dd-MMM-yy", "yyyy-MM-dd", "MM/dd/yy", "MM/dd/yyyy" } } )]
    public DateTime DateTime { get; set; }
}

请注意,在 JsonConverterAttribute 构造函数和您的构造函数中使用 params 可能会让人认为正确的语法是

[JsonConverter(typeof(CustomDateConverter), new object [] { "dd-MMM-yy", "yyyy-MM-dd", "MM/dd/yy", "MM/dd/yyyy" } )]

但是,这是行不通的。 Json.NET 通过 Type.GetConstructor(Type []) 查找具有适当签名的构造函数 - 构造函数的反射签名显示一个参数,即字符串数组。

fiddle.