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
}
}
As you can see, the converter's constructor has a variable number of params
string arguments, corresponding to all acceptable DateTime
formats. My question is how can I apply such a converter using JsonConverterAttribute
?