问题
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