簡體   English   中英

解析多個相同密鑰的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM