Rajesh Kumar Verma
Rajesh Kumar Verma

Reputation: 23

Not able to deserialize JSON array into C# list

I have a json array as below

{
"odata.metadata": "https://testapp.mycomp.com/$metadata#UnitDetail",
"value": [
    {
        "Id": 1,
        "UnitId": 238905,
        "Active": false,
        "Name": "Rakesh",
        "ContactNumber": "0070002934"           
    },
    {
        "Id": 2,
        "UnitId": 238906,
        "Active": true,
        "Name": "Rahul",
        "ContactNumber": "123444003"
    },
    {
        "Id": 3,
        "UnitId": 238907,
        "Active": true,
        "Name": "Rohit",
        "ContactNumber": "1227032932"
    }
]

}

I am trying to deserialize it into c# list as below

 var data= JsonConvert.DeserializeObject<UnitDetail[]>(json);

My c# class is a below

  public class UnitDetail
{
    public int Id { get; set; }
    public int UnitId { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
    public string ContactNumber { get; set; }

}

But this code is not deserializing it.

I have also tried codes as below but none seems working

  JavaScriptSerializer js = new JavaScriptSerializer();
  UnitDetail[] serializedData= js.Deserialize<UnitDetail[]>(json);

and also like below

List<UnitDetail> serializedData= js.Deserialize<List<UnitDetail>>(json);

I am really not sure why it is not working. Any help would really be appriciable.

Thanks

Upvotes: 2

Views: 687

Answers (2)

Microsoft DN
Microsoft DN

Reputation: 10030

Try using JsonHelper.Deserialize

List<UnitDetail> data = JsonHelper.Deserialize<List<UnitDetail>>(json);

Upvotes: -1

Eser
Eser

Reputation: 12546

You need a root object

public class UnitDetail
{
    public int Id { get; set; }
    public int UnitId { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
    public string ContactNumber { get; set; }
}

public class RootObject
{
    [JsonProperty("odata.metadata")]
    public string odata_metadata { get; set; }
    public List<UnitDetail> value { get; set; }
}

Now you can deserialize as

 var root = js.Deserialize<RootObject>(json);

Upvotes: 4

Related Questions