问题
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.
回答1:
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");
回答2:
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
}
回答3:
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.
来源:https://stackoverflow.com/questions/26372250/accessing-items-in-an-json-net-jarray-in-c-sharp