简体   繁体   English

如何解析此 JSON object 以获取我可以使用的配方对象列表?

[英]How do I parse this JSON object to get a list of recipe objects that I can then use?

So I am incredibly new to Java and am needing help parsing a JSON response.所以我对 Java 非常陌生,需要帮助来解析 JSON 响应。 I already have the method in which I am using to do so, but need help figuring out what exactly I am doing wrong.我已经有了我用来这样做的方法,但需要帮助弄清楚我到底做错了什么。

I am using an API to retrieve recipes from a site.我正在使用 API 从站点检索食谱。 I am trying to get a list of recipes ("hits" in this case I assume?) that I can then show to the user.我正在尝试获取食谱列表(在这种情况下我假设为“命中”?),然后我可以向用户展示。

Obviously I need the recipe name ("label" in this case) and other information.显然我需要配方名称(在这种情况下为“标签”)和其他信息。 Can anyone help me?谁能帮我?

Here is the response api response I am getting:这是我得到的响应 api 响应:

{
   "q": "chicken",
   "from": 0,
   "to": 10,
   "more": true,
   "count": 168106,
   "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,
            "dietLabels": [
               "Low-Carb"
            ],
            "healthLabels": [],
            "cautions": [],
            "ingredientLines": [
               "1/2 cup olive oil",
               "5 cloves garlic, peeled",
               "2 large russet potatoes, peeled and cut into chunks",
               "1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
               "3/4 cup white wine",
               "3/4 cup chicken stock",
               "3 tablespoons chopped parsley",
               "1 tablespoon dried oregano",
               "Salt and pepper",
               "1 cup frozen peas, thawed"
            ],
            "ingredients": [
               {
                  "text": "1/2 cup olive oil",
                  "weight": 108
               },
               {
                  "text": "5 cloves garlic, peeled",
                  "weight": 15
               },
               {
                  "text": "2 large russet potatoes, peeled and cut into chunks",
                  "weight": 532.5
               },
               {
                  "text": "1 3-4 pound chicken, cut into 8 pieces (or 3 pound chicken legs)",
                  "weight": 1587.5732
               },
               {
                  "text": "3/4 cup white wine",
                  "weight": 169.5
               },
               {
                  "text": "3/4 cup chicken stock",
                  "weight": 180
               },
               {
                  "text": "3 tablespoons chopped parsley",
                  "weight": 11.4
               },
               {
                  "text": "1 tablespoon dried oregano",
                  "weight": 6
               },
               {
                  "text": "Salt and pepper",
                  "weight": 16.46384
               },
               {
                  "text": "Salt and pepper",
                  "weight": 8.23192
               },
               {
                  "text": "1 cup frozen peas, thawed",
                  "weight": 134
               }
            ],
            "calories": 4055.7632,
            "totalWeight": 2765.59,
            "totalTime": 60,
            "totalNutrients": {},
            "totalDaily": {},
            "digest": []
         },
         "bookmarked": false,
         "bought": false
      },
      {
         "recipe": {
            "uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_8275bb28647abcedef0baaf2dcf34f8b",
            "label": "Chicken Paprikash",
            "image": "https://www.edamam.com/web-img/e12/e12b8c5581226d7639168f41d126f2ff.jpg",
            "source": "No Recipes",
            "url": "http://norecipes.com/recipe/chicken-paprikash/",
            "shareAs": "http://www.edamam.com/recipe/chicken-paprikash-8275bb28647abcedef0baaf2dcf34f8b/chicken",
            "yield": 4,
            "dietLabels": [],
            "healthLabels": [],
            "cautions": [],
            "ingredientLines": [],
            "ingredients": [],
            "calories": 3033.2012,
            "totalWeight": 1824.6125,
            "totalTime": 0,
            "totalNutrients": {},
            "totalDaily": {},
            "digest": []
         },
         "bookmarked": false,
         "bought": false
      },
      {
         "recipe": {
            "uri": "http://www.edamam.com/ontologies/edamam.owl#recipe_584ac5e486c088b3c8409c252d7f290c",
            "label": "Chicken Gravy",
            "image": "https://www.edamam.com/web-img/fd1/fd1afed1849c44f5185720394e363b4e.jpg",
            "source": "Martha Stewart",
            "url": "http://www.marthastewart.com/332664/chicken-gravy",
            "shareAs": "http://www.edamam.com/recipe/chicken-gravy-584ac5e486c088b3c8409c252d7f290c/chicken",
            "yield": 6,
            "dietLabels": [],
            "healthLabels": [],
            "cautions": [],
            "ingredientLines": [],
            "ingredients": [],
            "calories": 1092.3606,
            "totalWeight": 1590.8628,
            "totalTime": 270,
            "totalNutrients": {},
            "totalDaily": {},
            "digest": []
         },
         "bookmarked": false,
         "bought": false
      },
      {},
      {},
      {},
      {},
      {},
      {},
      {}
   ]
}

This is currently the method I am using to parse the JSON object:这是目前我用来解析 JSON object 的方法:

public void onResponse(Call call, Response response) throws IOException {

                    if (response.isSuccessful()) {
                        final String myResponse = response.body().string();
                        getActivity().runOnUiThread(new Runnable() {
                            private Object Date;

                            @Override
                            public void run() {
                                String jsonData = myResponse;
                                query_result.setText(myResponse);
                                Log.d("response5", myResponse);
                                //JSONObject jsonData1 = new JSONObject(myResponse);
                                JSONObject Jobject = null;
                                try {
                                    Jobject = new JSONObject(jsonData);
                                    Log.d("jobject", Jobject.toString());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                JSONArray Jarray = null;
                                try {
                                    Jarray = Jobject.getJSONArray("hits");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                for (int i = 0; i < Jarray.length(); i++) {
                                    JSONObject object;
                                    try {
                                        object = Jarray.getJSONObject(i);
                                        try {
                                            JSONArray Recipe = object.getJSONArray("recipe");
                                        }catch (JSONException e){
                                            e.printStackTrace();
                                        }
                                        for (int j = 0; j < Jarray.length(); j++){
                                            JSONObject object2 = null;
                                            try {
                                                object2 = Jarray.getJSONObject(j);
                                                String Name = object2.getString("label");
                                                String Photo = object2.getString("image");
                                                Log.d("rec_query", " " + Photo);
                                            }catch (JSONException e){
                                                e.printStackTrace();
                                                Log.d("response6:", e.toString());
                                            }
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        });
                    }
                }
            });

            return null;
        }
    }

NOTE THE {} {} are just different recipes...it wouldnt fit the whole response注意 {} {} 只是不同的配方...它不适合整个响应

At the moment, when I try to print my variables in the Log, I am getting a message that says the variable is empty (the variable that i used to store the different recipes/"hits".目前,当我尝试在日志中打印我的变量时,我收到一条消息,指出变量为空(我用来存储不同配方/“命中”的变量。

Your response seems incomplete, it's not in the correct JSON format,Provide the right format and I'll try to help you您的回复似乎不完整,不是正确的 JSON 格式,提供正确的格式,我会尽力帮助您

     String s = "{\n" +
            "    \"a1\":\"1\",\n" +
            "    \"b2\":[\n" +
            "        {\n" +
            "            \"b21\":\"vb21\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"b22\":\"vb22\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    JSONObject object = JSON.parseObject(s);
    String vb21 = object.getJSONArray("b2").getJSONObject(0).getString("b21");

like this,and neep to import com.alibaba.fastjson But i dont`t know if you can use fastjson像这样,并且需要导入 com.alibaba.fastjson 但我不知道你是否可以使用 fastjson

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

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