anoopb
anoopb

Reputation: 543

accessing items in an json.net jarray in c#

My API returns

{
  "result": [
    {
      "id": "51473",
      "name": "serv-vc",
      "modifydate": "2014-10-09 18:29:48.033",
      "expirationoff": "false",
      "createdate": "",
      "scheduleoff": "false",
    }
  ],
  "status": 0
}

which I've stored as a JObject reponseobj

I'm having trouble figuring out how to access responseobj["result"][0]["id"].

Every time I try that, it gives an array about being out of bounds.

What am I missing?

I also tried

JArray resultarr = (JArray)responseobj.SelectToken("result");
resultarr[0]["id"] 

but have the same results.

Upvotes: 5

Views: 18585

Answers (4)

BIJIN PALAKKAL
BIJIN PALAKKAL

Reputation: 186

var Jobj = ((JObject)RequestObject)["data"];
foreach (JObject content in Jobj.Children<JObject>()) {
    foreach (JProperty prop in content.Properties()) {
        Console.WriteLine(prop.Name);//the column name
        Console.WriteLine(prop.Value.ToString());// column value
    }
}

Upvotes: 0

Assuming the response is in a string variable called response, this would do it:

JObject responseobj = JObject.Parse(response);
JObject result = (JObject)(responseobj.SelectToken("result") as JArray).First();
int id = result.Value<int>("id");

Upvotes: 3

Benjamin RD
Benjamin RD

Reputation: 12034

Try using:

JObject jObject = JObject.Parse( "{\"result\": [{\"id\": \"51473\", \"name\": \"serv-vc\", \"modifydate\": \"2014-10-09 18:29:48.033\", \"expirationoff\": \"false\", \"createdate\": \"\", \"scheduleoff\": \"false\", } ], \"status\": 0 }" );

And to access to the different nodes, you can use:

string name = jObject["result"]["name"].ToString();
string expirationoff = jObject["result"]["expirationoff"].ToString();

Or you can convert result in a new json a work on it

And to access to result you can do:

var result = jObject["result"][0];

Remember that you can have 0, 1, 2... x numbers of results in your json, then you need do reference to the first position.

Upvotes: 1

Noctis
Noctis

Reputation: 11763

Not sure what's your issue, but this seems to work for me :

static void Main(string[] args)
{
    JObject j = JObject.Parse(
        "{\"result\": [{\"id\": \"51473\", \"name\": \"serv-vc\", \"modifydate\": \"2014-10-09 18:29:48.033\", \"expirationoff\": \"false\", \"createdate\": \"\", \"scheduleoff\": \"false\", } ], \"status\": 0 }" );
    var res = j["result"];
    Console.Out.WriteLine(res); 
    // show an arrays

    var maybe = j["result"][0];
    Console.Out.WriteLine(maybe);
    // shows the first object in the array

    var fail = j["result"][0]["id"];
    Console.Out.WriteLine(fail);
    // shows 51473
}

Upvotes: 0

Related Questions