2016-05-17 47 views
0

因此,我有一個帶有三個字符串參數(名稱,成分,圖像)的Pizza對象。 ,我有以下格式的JSON字符串:Android studio:如何在另一個JSON對象中循環JSON對象

{"Meat pizza":{"Ingredients":"cheese,meat","image":"meat"},"Cheese pizza":{"Ingredients":"cheese","image":"cheese"}} 

我以爲是一個JSON對象中JSON對象。 我使用凌空庫,到目前爲止,我想出了這個:

private RequestQueue queue = Volley.newRequestQueue(this); 
private String url ="http://daviddurand.info/D228/pizza/"; 
public ArrayList<Pizza> listPizza(){ 
    final ArrayList<Pizza> list=new ArrayList<>(); 
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        JSONObject obj = null; 
        try { 
         obj = new JSONObject(response); 
         Iterator<String> iter = obj.keys(); 
         while (iter.hasNext()) { 
          String key = iter.next(); 
          try { 
           Pizza pizza=new Pizza(); 
           Object value = obj.get(key); 
           //fill the Pizza object with data 
           pizza.setName(); 
           pizza.setIngredients(); 
           pizza.setImage(); 
           //insert it into the list 
           list.add(pizza); 
          } catch (JSONException e) { 
           // Something went wrong! 
          } 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      //error 
     } 
    }); 
// Add the request to the RequestQueue. 
     queue.add(stringRequest); 
     return list; 
    } 

正如你可能已經猜到已經什麼都不做,到目前爲止,因爲我不知道如何獲取數據來填充比薩對象。 。

注:這是值得一提的是,我不能修改數據是如何創建的看到,因爲我是如何被迫使用它here

回答

0

我沒有測試過這一點,你可以在裏面的JSONObject從JSONObject的

Object value = obj.get(key); 
    //fill the Pizza object with data 
    pizza.setName(key); 
    JSONObject jsonobject2 = obj.getJSONObject(key); 
    pizza.setIngredients(jsonobject2.getString("ingredients")); 
    pizza.setImage(jsonobject2.getString("image"));  
0

你可以按照這個Tutorial我建議你使用對象數組改爲對象對象。喜歡這個形式:

[ 
    { 
    "name" : "Ravi Tamada", 
    "email" : "[email protected]", 
    "phone" : { 
     "home" : "08947 000000", 
     "mobile" : "9999999999" 
    } 
    }, 
    { 
    "name" : "Tommy", 
    "email" : "[email protected]", 
    "phone" : { 
     "home" : "08946 000000", 
     "mobile" : "0000000000" 
    } 
    } 
] 

它更容易。我希望這會很有用。

+0

得到使用對象的數組將是令人愉快的,但我怕我沒有選擇這裏,看到如何我需要從這裏獲取數據http://daviddurandrand.info/D228/pizza/ – Ilias