Reputation: 1105
I've this json:
{
"status": true,
"Text": "Example"
}
But sometimes this could change, so I need to check if the index Text is available in the response passed, code:
var container = (JContainer)JsonConvert.DeserializeObject(response);
var message = container["Text"];
the problem is that I get this exception on message (if the json doesn't contain the key text
):
{"Accessed JArray values with invalid key value: \"Text\". Int32 array index expected."}
How can I avoid this problem?
Upvotes: 1
Views: 4100
Reputation: 9281
What version of NewtonSoft are you using?
The following results in message
being null and no exception is thrown.
var res = @"{""status"": true }";
var container = (JContainer)JsonConvert.DeserializeObject(res);
var message = container["Text"];
// message = null
Update:
Following your response, even this doesn't throw the exception you're seeing:
var res = @"{}";
var container = (JContainer)JsonConvert.DeserializeObject(res);
var message = container["Text"];
Having updated my code to reflect yours with the same version I'm still not getting the exception you're seeing. This is what I'm doing:
var res = @"{""trace"":{""details"":{""[date]"":""[29-02-2016 17:07:29.773750]"",""[level]"":""[info]"",""[message]"":""[System Done.]""},""context"":[[{""ID"":""John Dillinger""}]]}}";
var container = (JContainer)JsonConvert.DeserializeObject(res);
var message = container["Text"];
The message
variable is still null.
In light of this perhaps try create a simple console application with the above code and see if you get the same exception?
Upvotes: 1