处理JSON单个对象和数组

gil*_*uck 8 c# arrays json json.net

我正在使用Newtonsoft.Json处理一些返回给我的JSON数据.根据我的要求,我可以得到一些看起来像:

{
"TotalRecords":2,
"Result":
    [
        {
        "Id":24379,
        "AccountName":"foo"
        },
        {
        "Id":37209,
        "AccountName":"bar"
        }
    ],
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
Run Code Online (Sandbox Code Playgroud)

要么

{
    "Result":
    {
        "Id":24379,
        "AccountName":"foo"
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}
Run Code Online (Sandbox Code Playgroud)

因此,有时"结果"是结果数组,或者"结果"可能是单个响应.

我尝试使用如何使用JSON.net处理同一属性的单个项目和数组的答案,但我仍然得到错误.

特别是我得到了一个

Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...
Run Code Online (Sandbox Code Playgroud)

定制转换器看起来像:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的回复类看起来像

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; }
    }
Run Code Online (Sandbox Code Playgroud)

最后我的请求看起来像

List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ari 11

你的代码很好,它只需要一些类型的调整.

这条线

List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
Run Code Online (Sandbox Code Playgroud)

需要像这样,因为你的回答是object,而不是List.

TestResponse list = JsonConvert.DeserializeObject<TestResponse>(response);
Run Code Online (Sandbox Code Playgroud)

然后是您的自定义反序列化器属性:

[JsonConverter(typeof(SingleOrArrayConverter<string>))]
Run Code Online (Sandbox Code Playgroud)

需要成为:

[JsonConverter(typeof(SingleOrArrayConverter<DeserializedResult>))]
Run Code Online (Sandbox Code Playgroud)

因为你的Result对象不是s stringstrings 数组,所以它是DeserializedResults或a 的数组DeserializedResult.