2017-09-16 77 views
0

我想解析这个JSON在Volley库。我已经设置了我想要解析食谱和图像名称的所有内容。问题是我想同时解析三个食谱,但在这里它具有相同的对象名称配方,我不知道如何解析三个不同TextView的相同对象名称。我想分析这个JSON与凌空,但我不能这样做

这里是JSON格式:link

这里是我试过的代码,但它给了我一个名字不是三个不同的名字:

try { 

    JSONArray list = response.getJSONArray("hits"); 

    Log.v ("MISH", "List: " + list); 

    for (int x = 0; x<list.length(); x++) { 
    JSONObject obj = list.getJSONObject(x); 
    JSONObject main = obj.getJSONObject("recipe"); 
    String label = main.getString("label"); 
    String image = main.getString("image"); 

    Picasso.with(getApplicationContext()).load(image).into(recipeOne); 

    Log.v("FISH", "NAME FATCH: " + label); 
    recipeOneText.setText(label); 

    } 
+0

您可以检查我的答案。 @Murtaza – KeLiuyue

回答

1

试试这个。

并使用optString在代码:

try { 
    if (TextUtils.isEmpty(response)) { 
    Toast.makeText(this, "response is null", Toast.LENGTH_SHORT).show(); 
    return; 
    } 

    JSONObject jsonObject = new JSONObject(response); 
    JSONArray hits = jsonObject.getJSONArray("hits"); 
    // edited here ,add data in your code 
    JSONObject jo1 = hits.getJSONObject(0); 
    hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0 
    hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1 
    hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2 

    for (int i = 0; i < hits.length(); i++) { 
    JSONObject jo = hits.getJSONObject(i); 
    JSONObject recipe = jo.getJSONObject("recipe"); 
    String label = recipe.optString("label"); 
    String image = recipe.optString("image"); 

    Picasso.with(getApplicationContext()).load(image).into(recipeOne); 

    Log.v("FISH", "NAME FATCH: " + label); 
    recipeOneText.setText(label); 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

编辑

// If your don't have to much data in your code , you can do like this . 
JSONObject jo1 = hits.getJSONObject(0); 
hits.put(0,jo1); // add jo1 JSONObject to the JSON array, the angle is 0 
hits.put(1,jo1); // add jo1 JSONObject to the JSON array, the angle is 1 
hits.put(2,jo1); // add jo1 JSONObject to the JSON array, the angle is 2 
+0

你能告诉我如何获取3个食谱与单解析?因为这样我一次只能得到一个配方而不是3. – Murtaza

+0

您应该在服务器中添加食谱JSONObject。 @Murtaza – KeLiuyue

+0

Hi Murtaza!你可以试试这个代码。 – KeLiuyue

相关问题