1

I have a dictionary which uses classes for the keys and values. For those classes, I created JsonConverters to serialize/deserialize them in a specific way. To serialize the dictionary correctly, I used the following JsonConverter I found at https://newbedev.com/how-can-i-serialize-deserialize-a-dictionary-with-custom-keys-using-json-net.

public class CustomDictionaryConverter<TKey, TValue> : JsonConverter
{
    public override bool CanConvert(Type objectType) => objectType == typeof(Dictionary<TKey, TValue>);

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        => serializer.Serialize(writer, ((Dictionary<TKey, TValue>)value).ToList());

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        => serializer.Deserialize<KeyValuePair<TKey, TValue>[]>(reader).ToDictionary(kv => kv.Key, kv => kv.Value);
}

This does work, but the serialized dictionary entries are in this form

{"Key" : "KeyClass", Value" : "ValueClass"}

where KeyClass and ValueClass are the serialized outputs of the key and value classes. What I would like is to have each entry look like this

"KeyClass" : "ValueClass"

How do I do this?

Vic
  • 55
  • 7
  • You would need to have some way to roundtrip each instance of `KeyClass` from and to a string (specifically the property name) without loss of data. Do you have something like that? – dbc Aug 20 '21 at 04:42
  • 1
    The KeyClass also has a JsonConverter which is able to go from a string back to a key class through the JsonConverter's ReadJson method. – Vic Aug 20 '21 at 15:31

0 Answers0