0

Im having trouble in parsin JSON in C#. I want to parse this Json Format.

{
"data": 
  [
    {
        "id": 3,
        "code": "‎0000004", 
    }
  ]  
}

Here is my code in C#.

 public Data data { get; set; } 

 public class Data
 {
     public string id { get; set; }
     public string code { get; set; }
 }
ASanchez
  • 11
  • 4

3 Answers3

0

The JSON shown is an object that has (as data) an array of elements that have an id and code, so:

public class SomeRoot {
   public List<Data> data {get;} = new List<Data>();
}

and deserialize a SomeRoot and you should be fine:

var root = JsonConvert.DeserializeObject<SomeRoot>(json);
var obj = root.data[0];
Console.WriteLine(obj.id);
Console.WriteLine(obj.code);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

You are missing an essential part, the outer object. Also, the data is an array:

public class RootObject
{
    public Data[] data { get; set; } 
}

RootObject r = JsonConvert.DeserializeObject<RootObject>(json);

Next time, follow the steps as outlined in Easiest way to parse JSON response. It will help you generate the correct class.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

It should be :

public class Data
{
    public int id { get; set; }
    public string code { get; set; }
}

public class RootObject
{
    public List<Data> data { get; set; }
}
Rai Vu
  • 1,595
  • 1
  • 20
  • 30