这是我必须从网站上以JSON格式阅读文本。但我得到了错误
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;
}
}
答案 0 :(得分:2)
尝试更改以下行:
final JSONArray array = (JSONArray) JSONValue.parse(response);
为:
final JSONObject jsObj = (JSONObject) JSONValue.parse(response);
你能提供你想要解析的JSON字符串吗?即response
的价值?
答案 1 :(得分:0)
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes") ;
答案 2 :(得分:0)
org.json.simple.JSONObject无法强制转换为org.json.simple.JSONArray意味着您正在尝试将json对象转换为json数组。如果您在json对象中的响应作为响应,那么您首先需要它在Json对象中进行转换。
转换后,你可以使用get(“key-name”)从json对象获取Json数组JSONObject resObj = new JSONObject(responseString);
JSONArray resArray = resObj.getJSONArray("Username");
for (int i=0; i<resArray.length(); i++)
String resultString = resArray.getString(i);
它为您提供所有用户名。
我认为此代码可以帮助您解决问题。