這是我必須從網站閱讀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