0

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":[]}}.

1
  • Are you sure this is the data you are receiving? There is an extra pair of curly braces around the JSON, which makes it an invalid JSON. Commented Apr 21, 2016 at 4:30

3 Answers 3

3

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

Comments

2

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

Comments

1

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.