简体   繁体   中英

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.

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:

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 . Your JSON response is actually an array of one object and must be deserialized as such.

You need to deserialize the response into an array or list of JsonClasses.Item instead of into a single one, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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