尝试从此JSON文件中获取随机单词
public class Main {
public static void main(String[] args) {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/adjs.json");
JSONArray jsonArray = obj.getJSONArray("adjs");
for(int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.get(i));
}
Random r = new Random();
int id1 = r.nextInt(jsonArray.length());
String word1 = jsonArray.getJSONObject(id1).getString("adjs");
System.out.println(word1);
//String word = jsonArray.getJSONObject(r.nextInt(jsonArray.length())).getString("adjs");
}
}
有我正在使用的代码,但我不断收到此错误。
Exception in thread "main" org.json.JSONException: JSONArray[671] is not a JSONObject.
at org.json.JSONArray.getJSONObject(JSONArray.java:428)
at Job.Main.main(Main.java:23)
我该如何实现?
以下是我正在使用的JSON:
{
"description": "A list of English adjectives.",
"adjs":
[
"Aristotelian",
"Arthurian",
"Bohemian",
"Brethren",
"Mosaic",
"Oceanic",
"Proctor",
"Terran",
"Tudor",
"abroad",
"absorbing",
"abstract",
"academic",
"accelerated",
"accented",
"accountant",
"acquainted",
"acute",
"addicting",
"addictive",
"adjustable",
"admired",
"adult",
"adverse",
"advised"
]
}
寻找解决方法。哦,是的,它只是JSON文件的一小部分。
答案 0 :(得分:0)
String word1 = jsonArray.getJSONObject(id1).getString("adjs");
变量jsonArray
包含一个JSONArray
,其中包含字符串,而不是嵌套的JSONObject
。你想要的是
String word1 = jsonArray.getString(id1);
您实际编写的代码应采用以下格式的JSON:
{
"description": "A list of English adjectives.",
"adjs":
[
{ "adjs": "Aristotelian" },
{ "adjs": "Arthurian" },
...
]
}
在代码中两次提及键"adjs"
可能是一个线索:-)