Search code examples
javajsonjson-simple

Parse multiple of the same key JSON simple java


I'm not an expert at JSON so I'm not sure if I'm missing something obviously. But, what I'm trying to do is to parse this:

[{"name":"Djinnibone"},{"name":"Djinnibutt","changedToAt":1413217187000},{"name":"Djinnibone","changedToAt":1413217202000},{"name":"TEsty123","changedToAt":1423048173000},{"name":"Djinnibone","changedToAt":1423048202000}]

I don't want to get Djinnibone only the rest of the names following it. What I've managed to create is this. It give the right number of names. but they are all null. In this case null,null,null,null .

public String getHistory(UUID uuid) throws Exception {
    String history = "";
    HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
    JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
    JSONObject jsonObject = new JSONObject();
    for(int index = 1; index < response.size(); index++) {
        jsonObject.get(response.get(index));
        String name = (String) jsonObject.get("name");
        if(index < response.size()) {
            history = history + name + ",";
        } else {
            history = history + name + ".";
        }
    }
    return history == "" ? history = "none." : history;
}

Thanks for any help!


Solution

  • You're almost there, you're getting each JSONObject from the array but you're not using it correctly. You simply need to change your code like this in order to extract each object and use it directly, no need for an intermediate JSONObject creation:

    public String getHistory(UUID uuid) throws Exception {
        String history = "";
        HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
        JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        for(int index = 1; index < response.size(); index++) {
            JSONObject jsonObject = response.get(index);
            String name = (String) jsonObject.get("name");
            if(index < response.size()) {
                history = history + name + ",";
            } else {
                history = history + name + ".";
            }
        }
        return history == "" ? history = "none." : history;
    }