处理JSON单个对象和数组 [英] Handling JSON single object and array
问题描述
我正在使用Newtonsoft.Json处理返回给我的一些JSON数据.根据我的要求,我可以找回看起来像这样的东西:
I'm using Newtonsoft.Json to work with some JSON data that is being returned to me. Depending on what I request I can either get back something that looks like:
{
"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"
}
因此,有时结果"是结果的数组,或者结果"可能是单个响应.
So sometimes "Result" is an array of Results or "Result" could be a single response.
I've tried using the answer from How to handle both a single item and an array for the same property using JSON.net but I still get errors.
特别是我得到
Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...
自定义转换器看起来像:
Custom converter looks like:
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);
推荐答案
您的代码很好,它只需要进行一些类型的调整即可.
Your code is fine, it just needs a few type tweaks.
此行
List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
需要这样,因为您的回复是object
,而不是List
.
needs to be like this, because your response is an object
, not a List
.
TestResponse list = JsonConvert.DeserializeObject<TestResponse>(response);
然后您的自定义反序列化器属性:
Then your custom deserializer attribute:
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
需要成为:
[JsonConverter(typeof(SingleOrArrayConverter<DeserializedResult>))]
因为您的Result
对象不是string
或string
的数组,所以它是DeserializedResult
s或DeserializedResult
的数组.
because your Result
object is not a string
or an array of string
s, it's either an array of DeserializedResult
s or a DeserializedResult
.
这篇关于处理JSON单个对象和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!