您的 JSON 格式为:
[
{
"word":"apple",
"definitions":[
{
"string1":"this is string 1",
"string2":"this is string 2"
}
]
}
]
从问题看来您对 JSON 不太熟悉,learn more。
但现在你有一个JSON Array,其中包含JSON Object。又是 JSON Array 和 JSON Object。
所以要回答你的问题,你应该访问如下内容:
请注意,此代码可能存在一些错误,因为它未经测试。您有责任进行相应的修改。
第 1 步:
从JSON Array 获取JSON Object。您提供了一些代码,所以我将做出一些假设。
Item item = new Item(jsonObject.getString("word"),
jsonObject.getString("string1"), jsonObject.getString("string2"));
jsonObject 已经拥有来自外部数组的对象。如果是这种情况,请转到第 2 步。否则请继续阅读。
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");
第 2 步:
现在我们已经提取了密钥word 的value。让我们提取definitions。继续上一个示例。
// 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");
完整代码:
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");
那就是你必须先了解JSON Array 和JSON Object,然后才能了解原因和方法。