0

I have the following JSON Data, with hits having multiple recipe objects

"hits": [ { "recipe": { "uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_b79327d05b8e5b838ad6cfd9576b30b6", "label": "Chicken Vesuvio", "image": "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg", "source": "Serious Eats", "url": "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html", "shareAs": "http://www.edamam.com/recipe/chicken-vesuvio-b79327d05b8e5b838ad6cfd9576b30b6/chicken", "yield": 4,

However, I'm trying to get all the recipe objects which are children elements of hits Using this code

JSONArray recipeArray = null;

            JSONObject json = new JSONObject(jsonString);  //initial JSONObject (See explanation section below)

            JSONArray results = (JSONArray) json.get("hits");

            for(int i = 0; i < results.length(); i++){

                JSONObject resultObject = (JSONObject) results.get(i);
                JSONObject recipeobj = (JSONObject) resultObject.get("recipe");
                recipeArray.put(recipeobj);
            }

During runtime, recipeArray.put gives a handler exception. I have tried several methods on trying to do this such as looping the following

            JSONObject json = new JSONObject(jsonString);  
            JSONArray jsonArray = json.getJSONArray("hits");  
            JSONObject item = jsonArray.getJSONObject(i); JSONArray
            JSONArray recipeArray = item.getJSONArray("recipe");  

But gives a conversion error during the last line.

Any help or suggestions would be appreciated.

2
  • you can refer to this question : stackoverflow.com/questions/13963751/… Commented May 20, 2020 at 20:50
  • @Raushan That is not the issue, i did try it and it did not work. Thank you for your help tho :) Commented May 20, 2020 at 20:58

1 Answer 1

0

As your inner recipe object is not an array, it will throw JSONException for this

JSONArray recipeArray = item.getJSONArray("recipe");

And in your initial approach, recipeArray is not initialized which would have caused you NPE.

you can do like this

JSONArray recipes = new JSONArray();

JSONArray jsonArray = jsonObject.getJSONArray("hits");
for (int i=0; i< jsonArray.length(); i++){
  JSONObject item = jsonArray.getJSONObject(i);
  JSONObject recipe = item.getJSONObject("recipe");

  recipes.put(recipe);
}
Sign up to request clarification or add additional context in comments.

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.