简体   繁体   English

处理程序错误:在 JSONArray (JAVA) 中插入 JSONObject 时

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

I have the following JSON Data, with hits having multiple recipe objects我有以下 JSON 数据,点击有多个配方对象

"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.在运行时,recipeArray.put 会给出一个处理程序异常。 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由于您的内部recipe object 不是数组,因此它将为此抛出JSONException

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

And in your initial approach, recipeArray is not initialized which would have caused you NPE.在您的初始方法中, recipeArray未初始化,这会导致您出现 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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