简体   繁体   English

JSON 数组响应 REST API,提取数据时出错 Z240AA2CEC4B29C56F3BEE520ADCEE8

[英]JSON Array response REST API, Error extracting data c#

I am trying to extract from a response, but when trying to DeserializeObject I get the following error.我正在尝试从响应中提取信息,但是在尝试 DeserializeObject 时出现以下错误。

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'JSonClasses+Item' because the type requires a JSON object (eg {\"name\":\"value\"}) to deserialize correctly. Cannot deserialize the current JSON array (eg [1,2,3]) into type 'JSonClasses+Item' because the type requires a JSON object (eg {\"name\":\"value\"}) to deserialize correctly.

My Response is:我的回应是:

[{"Odid":45606,"UserId":22728,"FirstName":"FirstName ","MiddleName":null,"LastName":"LastName","UserName":"FirstName.LastName","ExternalEmail":"email@yahoo.com","DefinedId":"12345","UniqueIdentifier":"null","Activation":{"IsActive":true},"DisplayName":"FirstName LastName"}]

Here is how I am trying to DeserializeObject this response:这是我尝试反序列化此响应的方式:

public class Activation
{
    public bool IsActive { get; set; }
}

public class Item
{
    public int OrgId { get; set; }
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string ExternalEmail { get; set; }
    public string OrgDefinedId { get; set; }
    public string UniqueIdentifier { get; set; }
    public Activation Activation { get; set; }
    public string DisplayName { get; set; }
}


var responceID= JsonConvert.DeserializeObject<JSonClasses.Item>(response.Content);

I also have tried to use the following method to convert it into a Dynamic object and then try to extract data into Item class but the same error occurs:我还尝试使用以下方法将其转换为动态 object,然后尝试将数据提取到项目 class 但发生相同的错误:

dynamic response2 = JsonConvert.DeserializeObject(response.Content); 

What am I doing wrong?我究竟做错了什么?

As the error says, the deserializer cannot deserialize the array into your class that requires an object .正如错误所说,反序列化器无法将数组反序列化为需要 object 的class Your JSON response is actually an array of one object and must be deserialized as such.您的 JSON 响应实际上是一个包含一个 object 的数组,因此必须反序列化。

You need to deserialize the response into an array or list of JsonClasses.Item instead of into a single one, eg:您需要将响应反序列化为JsonClasses.Item的数组或列表,而不是单个,例如:

List<JSonClasses.Item> items = JsonConvert.DeserializeObject<List<JSonClasses.Item>>(response.Content);

As an additional note, there is a mismatch between "Odid" in your posted response body and OrgId in your Item class, which may cause your deserialization to still fail.作为附加说明,您发布的响应正文中的"Odid"与您的项目OrgId中的 OrgId 不匹配,这可能会导致您的反序列化仍然失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM