如何解析此JSON对象以获取一个可以后续使用的食谱对象列表?

huangapple go评论104阅读模式
英文:

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

问题

这是我目前正在使用的解析 JSON 对象的方法:

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);
                
                try {
                    JSONObject Jobject = new JSONObject(jsonData);
                    Log.d("jobject", Jobject.toString());
                    
                    JSONArray Jarray = Jobject.getJSONArray("hits");
                    
                    for (int i = 0; i < Jarray.length(); i++) {
                        JSONObject object = Jarray.getJSONObject(i);
                        JSONObject recipeObject = object.getJSONObject("recipe");
                        
                        String name = recipeObject.getString("label");
                        String photo = recipeObject.getString("image");
                        
                        Log.d("rec_query", " " + name + " - " + photo);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

注意:{} {} 只是不同的食谱……它们不能包含整个响应内容。

目前,当我尝试在日志中打印我的变量时,我得到了一个消息,说这个变量是空的(用来存储不同的食谱/“hits”的变量)。

英文:

So I am incredibly new to Java and am needing help parsing a JSON response. 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. 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:

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

This is currently the method I am using to parse the 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(&quot;response5&quot;, myResponse);
                                //JSONObject jsonData1 = new JSONObject(myResponse);
                                JSONObject Jobject = null;
                                try {
                                    Jobject = new JSONObject(jsonData);
                                    Log.d(&quot;jobject&quot;, Jobject.toString());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                JSONArray Jarray = null;
                                try {
                                    Jarray = Jobject.getJSONArray(&quot;hits&quot;);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                for (int i = 0; i &lt; Jarray.length(); i++) {
                                    JSONObject object;
                                    try {
                                        object = Jarray.getJSONObject(i);
                                        try {
                                            JSONArray Recipe = object.getJSONArray(&quot;recipe&quot;);
                                        }catch (JSONException e){
                                            e.printStackTrace();
                                        }
                                        for (int j = 0; j &lt; Jarray.length(); j++){
                                            JSONObject object2 = null;
                                            try {
                                                object2 = Jarray.getJSONObject(j);
                                                String Name = object2.getString(&quot;label&quot;);
                                                String Photo = object2.getString(&quot;image&quot;);
                                                Log.d(&quot;rec_query&quot;, &quot; &quot; + Photo);
                                            }catch (JSONException e){
                                                e.printStackTrace();
                                                Log.d(&quot;response6:&quot;, 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".

答案1

得分: 1

你的回复似乎不完整,它不符合正确的 JSON 格式,请提供正确的格式,我会尝试帮助你。

英文:

Your response seems incomplete, it's not in the correct JSON format,Provide the right format and I'll try to help you

答案2

得分: 0

Sure, here's the translated code portion:

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

Please note that this code snippet uses the FastJSON library for JSON parsing, and you'll need to import com.alibaba.fastjson to use it.

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

like this,and neep to import com.alibaba.fastjson
But i dont`t know if you can use fastjson

huangapple
  • 本文由 发表于 2020年4月9日 13:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61114401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定