2

Let us say I have some data class

class MyData {
    public string SomeValue;
}

And I have a JsonConverter for this

class MyDataConverter : JsonConverter<MyData> {
    public override void WriteJson(JsonWriter writer, MyData value, 
        JsonSerializer serializer)
    {
        writer.WriteValue(value.SomeValue);
    }

    public override MyData ReadJson(JsonReader reader, Type objectType,
        MyData existingValue, bool hasExistingValue, JsonSerializer serializer) 
    {
        var readerValue = (string) reader.Value;
        return new MyData {SomeValue = readerValue};
    }
}

Now I can use this converter on classes containing instances of MyData. However, I can find no way to use this converter to convert instances of List<MyData>, e.g.

class ClassIWantToSerialize
{
    public List<MyData> SomeList;
}

Annotating [JsonConverter(typeof(MyDataConverter))] did not work (not surprisingly).

What would be the easiest way to go about this?

Christoph
  • 1,537
  • 13
  • 19
  • You could add your converter to the serialization settings (https://www.newtonsoft.com/json/help/html/SerializationSettings.htm#Converters), or just explicitly provide your converter as argument when using the JsonConvert.DeserializeObject method (https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm). Then the (de)serializer will use the converter whereever it has to (de)serialize a MyData instance... –  May 24 '19 at 11:48
  • @elgonzo The thing is that in reality, I have a generic converter and many realisations of that. I do not know how that could be realized in that case. Also, it would spread information about my data types to locations where it does not belong. – Christoph May 24 '19 at 12:46
  • @elgonzo Thanks. I feared that. I don't like it but it works. – Christoph May 24 '19 at 14:18
  • 2
    Can't you just set `[JsonProperty(ItemConverterType = typeof(JsonConverter))]` as shown in [Custom json serialization for each item in IEnumerable](https://stackoverflow.com/q/36580519) and [Serialize a container of enums as strings using JSON.net](https://stackoverflow.com/q/18640162)? – dbc May 24 '19 at 15:59
  • I deleted my previous comment. Using the JsonPropertyAttribute is obviously by far the much better solution than the suggestion i made in my now-deleted comment ;-) –  May 24 '19 at 20:44

0 Answers0