Search code examples
c#unity-game-enginemonovirtual-reality

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


Solution

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