raz erez
raz erez

Reputation: 89

How to get value of JArray dictionary by key

I have this json string:

[
   [
      {
         "Antibiotic after diagnosis":[
            "Azithromycin",
            "Ciprofloxacin HCl",
            "Ampicillin Sodium"
         ],
         "City":[
            "Tel Aviv",
            "Jerusalem"
         ]
      }
   ],
   [
      {
         "Antibiotic after diagnosis":"Azithromycin",
         "City":"Tel Aviv"
      },
      {
         "Antibiotic after diagnosis":"Ciprofloxacin HCl",
         "City":"Jerusalem"
      }
   ]
]

I deserialized this string:

data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>("*json str*");
JParameters = data[0] as JArray;
Debug.Log(JParameters["Antibiotic after diagnosis"]);

But when i run the code it crashed on the line (Debug.Log(JParameters["Antibiotic after diagnosis"]);) with the following error:

"ArgumentException: Accessed JArray values with invalid key value: "Antibiotic after diagnosis". Int32 array index expected."

Upvotes: 0

Views: 10748

Answers (2)

Prany
Prany

Reputation: 2143

One option is to get key, value from Jproperty.

var files = JArray.Parse(YourJSON);
foreach (JArray item in files.Children())
 {
      foreach (JObject obj in item.Children())
        {
           foreach (JProperty prop in obj.Children())
            {
               string key = prop.Name.ToString();
               string value = prop.Value.ToString();
            }

        }
 }

Upvotes: 0

user2556381
user2556381

Reputation:

The index into JParameters should be an integer as the error states. What you want is:
JParameters[0]["Antibiotic after diagnosis"]

The above code selects the first element, and then selects the value for the dictionary key "Antibiotic after diagnosis".

I recommend reading w3schools JSON to properly understand how JSON works.

Upvotes: 1

Related Questions