我不是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;
}
感谢您的帮助!
答案 0 :(得分: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;
}