2

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

1
  • What error you are getting in List<UnitDetail> serializedData= js.Deserialize<List<UnitDetail>>(json); This seems to be fine. Commented Sep 10, 2015 at 12:14

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

Try using JsonHelper.Deserialize

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

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.