我正在调用相同的 REST API,并从该 API 获得 JSON 对象形式的响应,在尝试反序列化它时,它会抛出错误,因为其中一个对象有时会作为列表或对象返回。
我展示了一些示例代码,其中
Address
有时作为列表返回,有时作为单个对象返回。
JSON 对象,返回
Address
和列表:
{
"ResponseStatus": {
"Code": "1",
"Description": "Success"
},
"Address": [
{
"City": "CLEVELAND",
"State": "OH",
"PostalCode": "44126",
"CountryCode": "US"
},
{
"City": "CLEVELAND",
"State": "WV",
"PostalCode": "26215",
"CountryCode": "US"
}
]
}
JSON 对象,返回
Address
作为对象:
{
"ResponseStatus": {
"Code": "1",
"Description": "Success"
},
"Address": {
"City": "CLEVELAND",
"State": "OH",
"PostalCode": "44126",
"CountryCode": "US"
}
}
我用来反序列化 JSON 对象的类:
public class Address
{
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class ResponseStatus
{
public string Code { get; set; }
public string Description { get; set; }
}
public class Response
{
public ResponseStatus ResponseStatus { get; set; }
public List<Address> Address { get; set; }
}
Response result = JsonConvert.DeserializeObject<Response>(response);
Response
:此变量在调用 REST API 后初始化。
您应该实现一个自定义 Json 转换器来处理不同类型的数据。
在下面的示例中,处理
Address
,它可能是数组或对象。
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class ObjectListConverter<T> : JsonConverter
where T : class, new()
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
t.WriteTo(writer);
}
public override List<T> ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
return JToken.Load(reader).ToObject<List<T>>();
}
else if (reader.TokenType == JsonToken.StartObject)
{
return new List<T> { JToken.Load(reader).ToObject<T>() };
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
throw new JsonException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<T>) || objectType == typeof(T);
}
}
将
ObjectListConverter
添加到 JsonConverterAttribute
中。
public class Response
{
public ResponseStatus ResponseStatus { get; set; }
[JsonConverter(typeof(ObjectListConverter<Address>))]
public List<Address> Address { get; set; }
}