这是我必须从网站阅读JSON格式的文本。但我得到的错误JSON存储为字符串。不能解析它 - Java
Java.lang.ClassCastException:org.json.simple.JSONObject不能 投地org.json.simple.JSONArray
这是推动我坚果。谁能帮忙?我也需要检查这个字符串的“用户名”的所有实例,并为他们每个运行一些东西。
public class CommandCheck implements CommandExecutor {
private String username;
private static String host = "example.com";
private URL url;
private String apiKey = main.getNode("API-KEY");
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg3) {
try {
this.url = new URL(CommandCheck.host);
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("x-api-key", this.apiKey);
}
conn.addRequestProperty("User-Agent", main.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
sender.sendMessage(response); //Im just dumping the raw String for the person running the command to see Debug mostly
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
sender.sendMessage("The Array appears to be empty");
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
username = (String) latestUpdate.get("Username");
sender.sendMessage("whitelist add" + username);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
sender.sendMessage("I think there is an API key issue");
} else {
sender.sendMessage("Problem of unknown orign");
}
return false;
}
}
您没有包含有问题的字符串。投注它是一个对象而不是数组,就像错误所说的那样。 – chrylis
{“redemptions”:[{“reward_id”:450491,“redemption_id”:1729333,“created_at”:“2017-01-05T00:42:41.949Z”,“退款”:假,“完成”:假,“ user_input“:{”Minecraft Username“:”Budderb123“},”username“:”budderbb123“},{”reward_id“:450491,”redemption_id“:1729314,”created_at“:”2017-01-05T00:41:08.881 Z“,”refunded“:false,”completed“:false,”user_input“:{”Minecraft用户名“:”Bigdaddy“},”用户名“:”dustinduse“}],”total“:2,”page_size“: 25} –
是的,这是一个带顶级密钥“redemptions”,“total”和“page_size”的JSON对象。不是数组。 – chrylis