You have your JSON as:
[
{
"word":"apple",
"definitions":[
{
"string1":"this is string 1",
"string2":"this is string 2"
}
]
}
]
From the question it looks like you are not much familiar with JSON, learn more.
But for now you have a JSON Array
, that contains JSON Object
. Which again has JSON Array
that has JSON Object
.
So to answer you question you should be accessing the contents like below:
Note that this code might have some errors because it's not tested. It's your responsibility to modify it accordingly.
Step 1:
Get the JSON Object
from the JSON Array
. You have some code provided so I'm going to make some assumptions.
Item item = new Item(jsonObject.getString("word"),
jsonObject.getString("string1"), jsonObject.getString("string2"));
jsonObject
already has the object from outer array. If this is the case move onto the Step 2. Else continue reading this.
String json = "your json here"; // paste your provided json here
JSONArray jsonArray = new JSONArray(json);
// get the object at index 0
JSONObject jsonObject = jsonArray.getJSONObject(0);
// get the "word" value here
String word = jsonObject.getString("word");
Step 2:
Now we have extracted the value
of key word
. Let us extract the definitions
. Continued from previous example.
// getting the json array for definition
JSONArray definitions = jsonObject.getJSONArray("definitions");
// get the object at index 1
// use loop if you want to get multiple values from this array
JSONObject first = definitions.getJSONObject(0);
// finally get your string values
String string1 = first.getString("string1");
String string2 = first.getString("string2");
Complete Code:
String json = "your json here"; // paste your provided json here
JSONArray jsonArray = new JSONArray(json);
// get the object at index 0
JSONObject jsonObject = jsonArray.getJSONObject(0);
// get the "word" value here
String word = jsonObject.getString("word");
// getting the json array for definition
JSONArray definitions = jsonObject.getJSONArray("definitions");
// get the object at index 1
// use loop if you want to get multiple values from this array
JSONObject first = definitions.getJSONObject(0);
// finally get your string values
String string1 = first.getString("string1");
String string2 = first.getString("string2");
And that is it you have to understand JSON Array
and JSON Object
before you can understand why and how.