有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JSON存储为字符串。似乎无法用Java解析它

这就是我必须从网站上阅读JSON格式的文本。但是我得到了错误

Java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

这让我快发疯了。有人能帮忙吗?我还需要检查“Username”的所有实例的这个字符串,并为每个实例运行一些东西

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;
    }
}

共 (3) 个答案

  1. # 1 楼答案

    组织。json。易于理解的无法将JSONObject强制转换为组织。json。易于理解的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);
    

    它给了你我的一切

    我认为这段代码可以帮助您解决问题

  2. # 2 楼答案

    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") ;
    
  3. # 3 楼答案

    尝试更改以下行:

    final JSONArray array = (JSONArray) JSONValue.parse(response);

    致:

    final JSONObject jsObj = (JSONObject) JSONValue.parse(response);

    您能提供您试图解析的JSON字符串吗?即response的值