Lodestone6
Lodestone6

Reputation: 166

How to create an array from a JSON object in C# using JSON.Net

I am receiving the following JSON object as a server response to a GET request:

{{  "data": [    {      "role_id": "1",      "role_name": "Administrator"    },    {      "role_id": "2",      "role_name": "Operator"    }  ]}}

I am trying to create an array of "role_id" and a separate array of "role_name". Then, I want to add each member of the "role_name" array to a combobox. right now I am using Newtonsoft.Json.Linq to do the following:

JObject par = JObject.Parse(res);
        foreach(string s in (string)par["data"]))
            {
        }

        string role = (string)par["data"]["role_id"];
        string name = (string)par["data"]["role_name"];
        this.cmbRoleID.Items.Add(name.ToString());

I'm wondering how I can use a foreach loop or something to make this happen no matter how many pairs of role_id and role_name are sent in the {{"data":[]}}.

Upvotes: 0

Views: 3607

Answers (3)

Colin
Colin

Reputation: 4135

Simple. Minimal lines of code if you use "dynamic". For:

{  
   "data":[  
      {  
         "role_id":"1",
         "role_name":"Administrator"
      },
      {  
         "role_id":"2",
         "role_name":"Operator"
      }
   ]
}

Do something like this:

dynamic parsedObj = JsonConvert.DeserializeObject(json);

foreach(var child in parsedObj.data)
{
   var roleId = child.role_id;
   var roleName = child.role_name;
   //now do something with them.
}

Upvotes: 2

Bon Macalindong
Bon Macalindong

Reputation: 1320

Why not deserialize the json string into a class? Create your classes that map to a JSON structure of yours

public class Data
{
    public string role_id { get; set; }
    public string role_name { get; set; }
}

public class RootObject
{
    public List<Data> data { get; set; }
}

Then deserialize it and loop through like you normally would when looping array of objects.

var result = JsonConvert.DeserializeObject<RootObject>(res);
foreach(var item in result.data)
{
   //item.role_id, item.role_name
   //Your logic here.
}

Upvotes: 3

Nathan Bierema
Nathan Bierema

Reputation: 1923

You can use a for loop to loop through the JSON like this:

JObject par = JObject.Parse(res);
foreach(JToken data in par["data"].Children()))
{
    string role = data["role_id"].ToString();
    string name = data["role_name"].ToString();
    this.cmbRoleID.Items.Add(name);
}

Upvotes: 1

Related Questions