【发布时间】:2019-03-20 18:51:44
【问题描述】:
我想让我的 json 反序列化器忽略具有不正确值的对象(如字符串代替 int)或为它们返回 null 并继续反序列化 json 文件的其余部分。
这是我的 json:
{
"requests":[
{
"clientId":"1",
"requestId":"1",
"name":"Bułka",
"quantity":"1",
"price":"10.00"
},
{
"clientId":"1",
"requestId":"2.1",
"name":"Chleb",
"quantity":"2",
"price":"15.00"
},
{
"clientId":"1",
"requestId":"2",
"name":"Chleb",
"quantity":"5",
"price":"15.00"
},
{
"clientId":"2",
"requestId":"1",
"name":"Chleb",
"quantity":"1",
"price":"10.00"
}
]
}
这是我要反序列化的类:
class RequestCollection
{
public List<Request> requests { get; set; }
public RequestCollection()
{
requests = new List<Request>();
}
}
class Request
{
public string clientId { get; set; }
public long requestId { get; set; }
public string name { get; set; }
public int quantity { get; set; }
public double price { get; set; }
public Request() { }
public Request(string clientID, long requestID, string name, int quantity, double price)
{
this.clientId = clientID;
this.requestId = requestID;
this.name = name;
this.quantity = quantity;
this.price = price;
}
}
这是我反序列化文件的方法:
requestCollectionLocal = JsonConvert.DeserializeObject<RequestCollection>(json);
如您所见,我在 json 文件的第二个对象中的 requestId 值不正确。我希望反序列化的结果只是 3 个其他对象或所有 4 个具有空值的对象,而不是不正确的对象。
【问题讨论】:
标签: c# json json.net json-deserialization