Web API - JsonConverter - Custom Attribute

微笑、不失礼 提交于 2019-12-11 01:52:33

问题


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))]

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?


回答1:


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

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" } )]

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.

fiddle.



来源:https://stackoverflow.com/questions/43376404/web-api-jsonconverter-custom-attribute

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