Search code examples
c#json.netjsonconverter

Newtonsoft custom converter, string array as parameter


I am trying to create custom json converter ,which can parse date using specified formats

public class MultiFormatDateConverter: JsonConverter {
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType) {
        return objectType == typeof (DateTime);
    }
    private readonly string[] _formats;

    public MultiFormatDateConverter(params string[] formats) {
        _formats = formats;
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        ....
    }
}

this is how I am trying to use it

public class MyClass{
[JsonConverter(typeof(MultiFormatDateConverter),"dd/MM/yyyy","dd/MM/yy")]
        public DateTime Date{get;set;}
    
}

Getting error

Newtonsoft.Json.JsonException : Error creating 'MultiFormatDateConverter'. ----> Newtonsoft.Json.JsonException : No matching parameterized constructor found for 'MultiFormatDateConverter'.

What am I missing?


Solution

  • It looks like JsonConverterAttribute doesn't support passing in constructor parameters as a params array. Some options would be to pass in a single string with a delimiter or have multiple constructors for different numbers of parameters. For example:

    With a single string, use a character that is unlikely to be used in the format string. This can be fragile though:

    public MultiFormatDateConverter(string formats)
    {
        _formats = formats.Split('~'); // Unlikely ~ would be used in a format string?
    }
    

    Multiple constructors:

    public MultiFormatDateConverter(string format1)
    {
        _formats = new[] { format1 };
    }
    
    public MultiFormatDateConverter(string format1, string format2)
    {
        _formats = new[] { format1, format2 };
    }
    
    public MultiFormatDateConverter(string format1, string format2, string format3)
    {
        _formats = new[] { format1, format2, format3 };
    }
    
    // etc.