2

我不是 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;
}

谢谢你的帮助!

4

1 回答 1

1

你快到了,你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;
}
于 2015-10-24T03:52:23.090 回答