Java 和简单的 json

Java and simple json

提问人:Даниел Димитров 提问时间:1/20/2015 更新时间:1/20/2015 访问量:119

问:

我正在尝试从 json 用户名中获取这是 json

[{"user_id":"1","username":"THEUSERNAME","count300":"0","count100":"0","count50":"0","playcount":"0","ranked_score":"0","total_score":"0","pp_rank":"0","level":"0","pp_raw":"0","accuracy":"0","count_rank_ss":"0","count_rank_s":"0","count_rank_a":"0","country":"0","events":[]}]

我的代码是

URL url = new URL("url");
        URLConnection c = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder b = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) b.append(line);
        String text = b.toString();
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(text);
        String username = (String) jsonObject.get("username");
        System.out.println(username);

还有我得到的错误

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at eu.dpp.ircbot.Ircbot.main(Ircbot.java:80)
Java JSON的

评论

1赞 Sotirios Delimanolis 1/20/2015
你对这个错误有什么不明白的?你知道JSON格式吗?
0赞 Knut Holm 1/20/2015
阅读此操作方法:theoryapp.com/parse-json-in-java

答:

4赞 Sebastiaan van den Broek 1/20/2015 #1

请注意原始字符串周围的 []。这表明它是一个 JSONArray 而不是一个 JSONObject,这正是你得到的异常告诉你的。有关 JSON 规范,请参阅 http://json.org/

实际对象被 {} 包围,您可能会感到困惑,因为数组中只有 1 个对象。但是您仍然必须将字符串视为数组,然后遍历其中的对象。