我收到一系列未经标准化的JSON文件,其中一个特定字段始终是一个数字,但有时会带引号,有时不带引号。
例如:有时:
{
"skinname": "Classic Red",
"drivername": "",
"country": "",
"team": "",
"number": "0",
"priority": 4
}
有时候:
{
"skinname": "Racing 125",
"drivername": "",
"country": "",
"team" : "Audi Motorsport",
"number": 125
}
最糟糕的情况:
{
"skinname": "",
"drivername": "",
"country": "",
"team": "",
"number": "",
"priority": 1
}
我使用 System.Text.Json.JsonSerializer.Deserialize<>() 进行反序列化到这个类:
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; }
}
我有一个类需要反序列化,但是有时候无论我将该值分配为字符串或整数都会出现错误。
我不能在字段的get;set;中处理它,所以我通过捕获错误来解决它,尝试将其反序列化为具有其他类型的类,然后将第二个类转换为第一个类,或者捕获最终错误...
我发现我的解决方法很糟糕,也许(很可能)有更好的方法来处理它。
编辑:根据Serge的评论,添加了更多细节。 编辑2:发现另一种情况,其中数字为“”,导致建议的解决方案失败