1

A very simple JSON like this (response.getBody().toString()):

{"per_page":50,"total":93,"last_page":2,"stars":[]}

Has some problems when I want to parse it:

JSONObject object = new JSONObject(response.getBody()); // no error
System.out.println(object.getJSONObject("total")); // not found

org.json.JSONException: JSONObject["total"] not found.

Other properties cannot be parsed either:

JSONArray startups = object.getJSONArray("stars");

org.json.JSONException: JSONObject["stars"] not found.


The key is to hold the value of response.getBody()

String json = response.getBody().toString();
3
  • 2
    Please post a minimal reproducible example, not snippets. Commented Feb 10, 2018 at 19:57
  • The code snippets look Ok so there must be an error in the other parts of the code. Commented Feb 10, 2018 at 20:00
  • I would rather create model to map that response and read the values. Commented Feb 10, 2018 at 20:09

3 Answers 3

3

Inside object total is not JSONObject it is an Int value, that's why you code crashing.

So use this

System.out.println(String.valueOf(object.getInt("total")));

instead of

System.out.println(object.getJSONObject("total")); 
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, because of the missing doublequotes, it might be a JsonNumber accessible using object.getJsonNumber("total"), but you are right about it not being an object.
It is actually an int. I tried getInt(), getString() and get(), same result
use System.out.println(object.getInt("total")+"")
before getting the value from object check the value is present or not. using object.has("total")
1
String json = "{\"per_page\":50,\"total\":93,\"last_page\":2,\"stars\":[]}":

JSONObject jsonObject = new JSONObject (json);

JSONArray jsonArray  = jsonObect.getJSONArray("stars");

int perPage = jsonObject.getInt("per_page");

try like this...

Comments

0

In addition to earlier answer, to parse array, use getJSONArray as

JSONArray ja = jsonObj.getJSONArray("stars");

You can loop-over the array as:

for(int j=0; j<ja.length(); j++) {
    JSONObject json = ja.getJSONObject(j);
    // do same as before for string, int or other data types
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.