I have a complex JSON object in which I have a dictionary that looks like this:
{
...
"SomeDictionary": {
"0x010": {
"a": "b"
},
"0x020": {
"a": "b"
},
"0x030": {
"a": "b"
}
}
...
}
in this dictionary the keys are represented as hexadecimal numbers, I'd like to read them into a Dictionary<uint, T> (where T is the type of the Values of the Dictionary).
This solution solves it by creating a converter for the whole dictionary: https://stackoverflow.com/a/7010231/3396104 but I'll have multiple of these dictionaries and I don't want to specify multiple converters for each case (not even with generics)
This solution solves it by type converters: JSON.NET not utilizing TypeConverter for Dictionary key but I don't want to wrap my dictionary key into a class.
Current (simplest) solution:
public record class ComplexObjectDTO(
...
Dictionary<string, MyType> SomeDictionary
...
)
Then when converting the DTO into a Domain object I wrote this little helper function:
private static Dictionary<uint, T> ToUintDictionary<T>(Dictionary<string, T> source) =>
source.ToDictionary(
x =>
{
var str = x.Key;
if (!str.StartsWith("0x"))
throw new Exception($"Expected hexadecimal number, got {str} instead");
return Convert.ToUInt32(str, 16);
},
x => x.Value
);
This is fine because I have a DTO object anyways, but I'm still looking for other solutions.