I receive a series of json files which are not standarized, and a specific field is always a number, but sometimes quoted and sometimes unquoted.
e.g: sometimes:
{
"skinname": "Classic Red",
"drivername": "",
"country": "",
"team": "",
"number": "0",
"priority": 4
}
sometimes:
{
"skinname": "Racing 125",
"drivername": "",
"country": "",
"team" : "Audi Motorsport",
"number": 125
}
And worst case:
{
"skinname": "",
"drivername": "",
"country": "",
"team": "",
"number": "",
"priority": 1
}
I use System.Text.Json.JsonSerializer.Deserialize<>(), deserialized to this class:
public class JsonLiveryDetails
{
public string skinname { get; set; }
public string drivername { get; set; }
public string country { get; set; }
public string team { get; set; }
public string number { get; set; }
public int? priority { get; set; }
}
I have a class to deserialize into, but of course, sometimes I get an error whether I assign that value as string or int.
I cant't get to handle it in the get; set; of the field, so I workarounded it by catching the error, trying to deserialize it into a class with the other type and then convert the second class into the first, or catching a final error...
I find my workaround dirty, maybe (probabliy) there is a better way to handle it.
EDIT: Following Serge comments, added more details. EDIT2: Found another case, where number is "" and makes proposed solution to fail