【发布时间】:2017-10-21 08:59:21
【问题描述】:
我正在使用 Newtonsoft.Json 处理一些返回给我的 JSON 数据。根据我的要求,我可以取回如下所示的内容:
{
"TotalRecords":2,
"Result":
[
{
"Id":24379,
"AccountName":"foo"
},
{
"Id":37209,
"AccountName":"bar"
}
],
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
或
{
"Result":
{
"Id":24379,
"AccountName":"foo"
},
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
所以有时“结果”是一个结果数组,或者“结果”可能是单个响应。
我尝试使用来自How to handle both a single item and an array for the same property using JSON.net 的答案,但我仍然遇到错误。
特别是我得到了一个
Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...
自定义转换器如下所示:
public class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objecType)
{
return (objecType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objecType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
我的响应类看起来像
public class TestResponse
{
[JsonProperty("Result")]
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
public List<DeserializedResult> Result { get; set; }
}
public class DeserializedResult
{
public string Id { get; set; }
public string AccountName { get; set; }
}
最后我的请求看起来像
List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
【问题讨论】:
-
你只有两种答案吗?
-
他们只会遵循这两种格式中的一种,尽管内容显然会有所不同。有时“结果”会有多个字段,有时只有一个或两个,无论它返回单个对象还是最多 100 个对象的数组。
-
现在我将尝试编写代码解决方案。