【问题标题】:JSON stored as string. Cant seem to parse it - JavaJSON 存储为字符串。似乎无法解析它 - Java
【发布时间】:2017-01-05 05:34:30
【问题描述】:

这是我必须从网站读取 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;
    }
}

【问题讨论】:

  • 您没有包含有问题的字符串。就像错误所说的那样,赌它是一个对象而不是一个数组。
  • { "redemptions":[ { "reward_id":450491, "redemption_id":1729333, "created_at":"2017-01-05T00:42:41.949Z", "refunded":false, “完成”:假,“用户输入”:{“我的世界用户名”:“Budderb123”},“用户名”:“budderbb123”},{“reward_id”:450491,“redemption_id”:1729314,“created_at”:“2017- 01-05T00:41:08.881Z", "refunded":false, "completed":false, "user_input": { "Minecraft Username":"Bigdaddy" }, "username":"dustinduse" } ], "total" :2, "page_size":25 }
  • 是的,这是一个带有顶级键 redemptionstotalpage_size 的 JSON 对象。不是数组。
  • 好的。那么我需要先转换为数组吗?对吗?

标签: java json


【解决方案1】:

尝试更改以下行:

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

到:

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

您能否提供您尝试解析的 JSON 字符串? IE。 response 的值?

【讨论】:

  • { "redemptions":[ { "reward_id":450491, "redemption_id":1729333, "created_at":"2017-01-05T00:42:41.949Z", "refunded":false, “完成”:假,“用户输入”:{“我的世界用户名”:“Budderb123”},“用户名”:“budderbb123”},{“reward_id”:450491,“redemption_id”:1729314,“created_at”:“2017- 01-05T00:41:08.881Z", "refunded":false, "completed":false, "user_input": { "Minecraft Username":"Bigdaddy" }, "username":"dustinduse" } ], "total" :2, "page_size":25 }
【解决方案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】:

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

    它为您提供所有用户名。

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

    【讨论】:

    • 这个答案对我来说最有意义。如何将对象转换为数组?
    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2013-11-26
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多