Web API-JsonConverter-自定义属性 [英] Web API - JsonConverter - Custom Attribute

查看:166
本文介绍了Web API-JsonConverter-自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are having a web api project and inorder to convert the date time to date and vice versa, we are using DateTimeconverter extended from JsonConverter. We are using this in the form of an attribute for all the required DateTime properties (as shown below):

[JsonConverter(typeof(CustomDateConverter))]

CustomDateConverter如下:

The CustomDateConverter is as below:

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

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

My question is how can i define a custom constructor while using the attribute?

推荐答案

您可以使用 ConverterParameters 属性:

You can use the [JsonConverterAttribute(Type,Object[])] attribute constructor to pass arguments to your CustomDateConverter when it is constructed by Json.NET. This constructor automatically sets the ConverterParameters property:

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构造函数,并且在您的构造函数中可能会导致人们认为正确的语法是

Note that the use of params in the JsonConverterAttribute constructor and in your constructor might lead one to think that the correct syntax is

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

但是,这将不起作用. Json.NET通过 Type.GetConstructor(Type []) -并且构造函数的反射签名显示了一个参数,即一个字符串数组.

However, this will not work. Json.NET looks for a constructor with the appropriate signature via Type.GetConstructor(Type []) - and your constructor's reflected signature shows one single parameter, namely an array of strings.

小提琴.

这篇关于Web API-JsonConverter-自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆