Renu R
Renu R

Reputation: 69

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 (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Client.Details]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. 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!

Upvotes: 0

Views: 3487

Answers (3)

Orif Khodjaev
Orif Khodjaev

Reputation: 1102

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

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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.

Upvotes: 0

Servy
Servy

Reputation: 203823

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

Upvotes: 2

Related Questions