Reputation: 33
I am trying to get from a json username this is the 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":[]}]
My code is
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);
And the error i get
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)
Upvotes: 0
Views: 124
Reputation: 6331
Note the [] around your original string. This indicates that it's a JSONArray and not a JSONObject, which is exactly what the exception you get tells you. For the JSON specs, see http://json.org/
The actual object is surrounded with {}, you may be confused because you only have 1 object inside the array. But you still have to treat the string as an array and then iterate over the objects in it.
Upvotes: 4