Reputation: 21
I am obtaining a JSON response from an API which contains color information.
This is the response:
I want to be able to access the html_code value from the background_colors array within the info JSON object.
Firstly, have tried doing this simply with this code:
result = stack.getBody().getObject().toString(2);
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
This prints me out the info Object as expected.
However, if I try and access the JSON Array "background_colors" using this,
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
JSONArray jsonArray =
jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
I get this error: No value for "background_colors".
I know this error means that the background_colors array does not exist in the JSONObject but I have no idea how and why this would be the case?
Any help would be much appreciated.
Upvotes: 1
Views: 169
Reputation: 539
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");
Upvotes: 0
Reputation: 22474
background_colors
is a property of the info
object not the root object from the array.
Try this:
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
Upvotes: 1