我正在尝试使用 JSON.NET 库从 oodle.com api 提要中解析出数据。要反序列化的响应 JSON 字符串的一部分具有以下“位置”结构:
"location":{
"address":"123 foo Street",
"zip":"94102",
"citycode":"usa:ca:sanfrancisco:downtown",
"name":"San Francisco (Downtown)",
"state":"CA",
"country":"USA",
"latitude":"37.7878",
"longitude":"-122.4101"},
但是我已经看到 location 的实例被声明为一个空数组:
"location":[],
我正在尝试将它反序列化为一类位置数据。当 location 中有有效数据时,这很有效,但当 location 表示为空数组时,它不能很好地工作。如果数据确实是空数组,我尝试添加属性(NullValueHandling 和必需)以将位置实例设置为 null,但我认为这些属性仅用于序列化。如果数组为空,我会得到一个异常
Cannot deserialize JSON array into type 'LocationData'
如果数组反序列化失败,有没有办法告诉反序列化器不要提示并使位置对象为空?
谢谢!
[JsonProperty(NullValueHandling = NullValueHandling.Ignore,Required=Required.AllowNull)]
public LocationData location{get;set;}
...
public class LocationData
{
public string zip { get; set; }
public string address { get; set; }
public string citycode { get; set; }
public string name { get; set; }
public string state { get; set; }
public string country { get; set; }
public decimal latitude { get; set; }
public decimal longitude { get; set; }
}
最佳答案
您可以为 LocationData
编写自定义转换器type 将数组标记转换为 null。
就像是:
public class LocationDataConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.Read(); //move to end array
return null;
}
var data = new LocationData();
serializer.Populate(reader, data);
return data;
}
}
然后只需标记 LocationData 类:
[JsonConverter(typeof(LocationDataConverter))]
public class LocationData {...}
关于json - 无法将 JSON 数组反序列化为 foo 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3691830/