简体   繁体   中英

Handler Error: When inserting JSONObject in a JSONArray (JAVA)

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM