Handling JSON single object and array

旧街凉风 提交于 2019-12-05 03:31:31

Your code is fine, it just needs a few type tweaks.

This line

List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);

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>))]

needs to become:

[JsonConverter(typeof(SingleOrArrayConverter<DeserializedResult>))]

because your Result object is not a string or an array of strings, it's either an array of DeserializedResults or a DeserializedResult.

I think, that there is no way to understend which type of response do you have due desirialization. Thats why i propose to check manualy type of response:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace TestConsoleApp
{
    public class Class1
    {

        public class Result
        {
            public int Id { get; set; }
            public string AccountName { get; set; }
        }

        public class ModelWithArray
        {
            public int TotalRecords { get; set; }
            public List<Result> Result { get; set; }
            public int ResponseCode { get; set; }
            public string Status { get; set; }
            public string Error { get; set; }
        }

        public class Result2
        {
            public int Id { get; set; }
            public string AccountName { get; set; }
        }

        public class ModelWithoutArray
        {
            public Result2 Result { get; set; }
            public int ResponseCode { get; set; }
            public string Status { get; set; }
            public string Error { get; set; }
        }

        public static void Main(params string[] args)
        {
            //string json = "{\"TotalRecords\":2,\"Result\":[{\"Id\":24379,\"AccountName\":\"foo\"},{\"Id\":37209,\"AccountName\":\"bar\"}], \"ResponseCode\":0,\"Status\":\"OK\",\"Error\":\"None\"}";
            string json = "{\"Result\":{\"Id\":24379,\"AccountName\":\"foo\"},\"ResponseCode\":0,\"Status\":\"OK\",\"Error\":\"None\"}";

            if (checkIsArray(json))
            {
                ModelWithArray data = JsonConver.DeserializeObject<ModelWithArray >(json);
            }else
            {
                ModelWithoutArray data = JsonConver.DeserializeObject<ModelWithoutArray>(json);
            }

        }

        static bool checkIsArray(string json)
        {

            Dictionary<string, object> desData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

            if (desData["Result"].GetType().Name.Contains("Array"))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!