解析多个相同的键 JSON 简单 java

Parse multiple of the same key JSON simple java

我不是 JSON 方面的专家,所以我不确定我是否遗漏了什么。但是,我要做的是解析这个:

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

我不想只获取 Djinnibone 后面的其余名称。我设法创造的是这个。它给出了正确数量的名字。但它们都是空的。在这种情况下 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;
}

感谢您的帮助!

您快完成了,您正在从数组中获取每个 JSONObject,但您没有正确使用它。您只需像这样更改代码即可提取每个对象并直接使用它,无需中间 JSONObject 创建:

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