【问题标题】:Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialze withGenerictype无法将 JSON 数组(例如 [1,2,3])反序列化为类型 ' ',因为类型需要 JSON 对象(例如 {"name":"value"})来反序列化 withGenerictype
【发布时间】:2021-09-27 09:17:08
【问题描述】:

这是我的 JSON

{
  "states": [
    {
      "state_id": 1,
      "state_name": "Andaman and Nicobar Islands"
    },
    {
      "state_id": 2,
      "state_name": "Andhra Pradesh"
    },
    {
      "state_id": 3,
      "state_name": "Arunachal Pradesh"
    },
    ...
    {
      "state_id": 36,
      "state_name": "West Bengal"
    }
  ],
  "ttl": 24
}

这是我的模型类


    public class State
    {
        [JsonConstructor]
        public State(int stateId,string stateName)
        {
            this.StateId = stateId;
            this.StateName = stateName;
        }

        [JsonPropertyName("state_id")]
        public int StateId { get; set; }

        [JsonPropertyName("state_name")]
        public  string StateName { get; set; }
    }

    public class ApiSevuModels
    {
        [JsonConstructor]
        public ApiSevuModels(List<State> states,int ttl)
        {
            this.States = states;
            this.Ttl = ttl;
        }

        [JsonPropertyName("states")]
        public  List<State> States { get; set; }

        [JsonPropertyName("ttl")]
        public int Ttl { get; set; }
    }

这是我用于反序列化的 Conttoller 类

namespace ExternalApi.demo.Controllers
{
    public class StatesController : Controller
    {

        // GET: States
        public async Task<ActionResult> Index()
        {
         IEnumerable<State> apiStates = null;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://cdn-api.co-vin.in/api/v2/admin/location/");
                client.DefaultRequestHeaders.Accept.Clear();
                //HTTP GET


                HttpResponseMessage result = await client.GetAsync("states");
                if (result.IsSuccessStatusCode)
                {
                    var part=result.ReasonPhrase;
                    var content = await result.Content.ReadAsStringAsync();
                 apiStates=JsonConvert.DeserializeObject<IList<State>>(content);
                }
                else //web api sent error response 
                {
                    //log response status here..

                   
                    
                    ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
                }
            }
            return View(apiStates);
        }
    }
}

而我的问题是,在运行此代码时,我得到了像 这样的期望,因为类型需要 JSON 对象(例如 {"name" :"value"}) 正确反序列化

【问题讨论】:

  • 您能否提供一个您收到的 JSON 示例。您可能会收到代表对象而不是数组的 JSON。
  • 您的 JSON 代表 ApiSevuModels 的一个实例,而不是 State 项目的集合。请改用JsonConvert.DeserializeObject&lt;ApiSevuModels&gt;(content)

标签: c# json asp.net-web-api json-deserialization webapi


【解决方案1】:

您的 JSON 表示 ApiSevuModels 的一个实例,根对象具有键 statesttl。它不是State 项目的集合,这是一个更深的层次。

要正确反序列化,您需要反序列化为 ApiSevuModels 的实例。

ApiSevuModels apiStates = null;
apiStates = JsonConvert.DeserializeObject<ApiSevuModels>(content);

这是dotnetfiddle showing the code working

【讨论】:

  • 但这也行不通
  • 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.IList`1[ExternalApi.demo.Models.ApiSevuModels]”,因为type 需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或 List)。
  • 这看起来像你原来的错误是在寻找一个 JSON 数组而不是一个 JSON 对象,你能仔细检查你试图反序列化的类型 - 它应该是 ApiSevuModels 而不是 IList&lt;State&gt; .
  • IEnumerable apiStates = null;
  • apiStates=JsonConvert.DeserializeObject>(content);
猜你喜欢
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多