简体   繁体   中英

How to convert JSON Response to a List in C#?

This might be a basic question but I am stuck while converting a JSON Response to a List. I am getting the JSON Response as,

{"data":[{"ID":"1","Name":"ABC"},{"ID":"2","Name":"DEF"}]}

Have defined a Class,

class Details
{
    public List<Company> data { get; set; }

}
class Company
{
    public string ID { get; set; }

    public string Name { get; set; }
}

Have tried this for converting,

List<Details> obj=List<Details>)JsonConvert.DeserializeObject
   (responseString,     typeof(List<Details>));

But this returns an error, saying

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[Client.Details]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Kindly help!

You don't have a List<Detail> defined in your JSON. Your JSON defines one Detail record, which itself has a list of companies.

Just deserialize using Details as the type, not List<Details> (or, if possible, make the JSON wrap the single detail record into a one item array).

You need to Deserialize like this:

var Jsonobject = JsonConvert.DeserializeObject<Details>(json);

using classes generated by json2csharp.com:

 
 
 
 
  
  
  var Jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
 
 
  

and your classes should be :

 
 
 
 
  
  
  public class Datum { public string ID { get; set; } public string Name { get; set; } } public class RootObject { public List<Datum> data { get; set; } }
 
 
  

you can always use json2csharp.com to generate right classes for the json.

You can use JavaScriptDeserializer class

string json = @"{""data"":[{""ID"":""1"",""Name"":""ABC""},{""ID"":""2"",""Name"":""DEF""}]}";
Details details = new JavaScriptSerializer().Deserialize<Details>(json);

EDIT: yes, there's nothing wrong with OP's approach, and Servy's answer is correct. You should deserialize not as the List of objects but as the type that contains that List

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