I work with devices that send their configuration in JSON:
{
"A": {
"AA": "1,customconverter,2019",
"AB": {
"ABA": "google.com",
"ABB": 25.0
}
},
"B": {
"BA": 100
}
}
Corresponding .NET classes:
class AA
{
public int X { get; set; }
public string Y { get; set; }
public DateTime Z { get; set; }
}
class AB
{
public string ABA { get; set; }
public double? ABB { get; set; }
}
class A
{
[JsonConverter(typeof(MyCustomJsonConverter))]
public AA AA { get; set; }
public AB AB { get; set; }
}
enum MyEnum
{
Unknown = 0,
Wow = 1,
Lol = 2
}
class B
{
public MyEnum BA { get; set; }
}
class Config
{
public A A { get; set; }
public B B { get; set; }
}
It may happen that some particular device doesn't have e.g. AB setting and instead of sending ordinary "null" or just omitting that field it sends "?" instead:
{
"A": {
"AA": "1,customconverter,2019",
"AB": "?"
},
"B": {
"BA": 100
}
}
It can happen for any field regardless if it's a string or not.
Config class is huge and deep. I use custom converters a lot. What I need is some approach that will convert this question mark "?" to default value if it's value type or null if it's nullable/class/reference type.
I thought about some global JsonConverter, but it seems I can't just make one JsonConverter applied for every possible type, becasue it has infinite recursion problems. It is easy to avoid it if converter is designed just for one type: https://stackoverflow.com/a/36116462/6440521 but how to avoid it if converter is applied for many types / global? Also I can fallback to some default behavior from custom JsonConverter: https://stackoverflow.com/a/35590069/6440521 but how to fallback to other converter (e.g. specified in property attribute) based on objectType (keeping in mind we're in global JsonConverter that handles many types)?
What is the best approach to do this in Json.NET?
EDIT: Currently my workaround is to replace every occurence of "?" with null before deserialization and use nullables everywhere (for value types)