简体   繁体   中英

Getting random string from JSON File

Trying to get a random word from this JSON file

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");
    }
}

There is the code I am using and I keep getting this error.

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)

How can I achieve it?

Below is the JSON I'm working with:

{
    "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"
    ]
}

Looking for ways around it. Oh yea is just a little bit of the JSON file.

String word1 = jsonArray.getJSONObject(id1).getString("adjs");

The variable jsonArray contains a JSONArray , which contains strings , not nested JSONObject s. What you want is

String word1 = jsonArray.getString(id1);

The code you actually wrote expects JSON in the following form:

{
    "description": "A list of English adjectives.",
    "adjs":
    [
        { "adjs": "Aristotelian" },
        { "adjs": "Arthurian" },
        ...
    ]
}

Mentioning the key "adjs" twice in your code could have been a clue :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM