Sometimes you run into things that might look trivial but it just do not work as expected. One such example is when you attempt to serialize/Deserialize a Dictionary with Tuples as the key. For example
var dictionary = new Dictionary<(string, string), int> { [("firstName1", "lastName1")] = 5, [("firstName2", "lastName2")] = 5 }; var json = JsonConvert.SerializeObject(dictionary); var result = JsonConvert.DeserializeObject<Dictionary<(string, string), string>>(json);
The above code would trow an JsonSerializationException when deserializing. But the good part is, the exception tells you exactly what needs to be done. You need to use an TypeConverter here.
Let’s define our required TypeConverter
public class TupleConverter<T1, T2> : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var elements = Convert.ToString(value).Trim('(').Trim(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return (elements.First(), elements.Last()); } }
And now, you can alter the above code as
TypeDescriptor.AddAttributes(typeof((string, string)), new TypeConverterAttribute(typeof(TupleConverter<string, string>))); var json = JsonConvert.SerializeObject(dictionary); var result = JsonConvert.DeserializeObject<Dictionary<(string, string), string>>(json);
With the magic portion of TypeConverter in place, your code would now work fine. Happy Coding.
How would you appropriate this to work with int touples?
LikeLike