2015-07-21 86 views
-3

如何在Android中解析2個json數組? Plz看到下面的代碼;Android:解析2 jsonArray

{ 
"detail": [ 
    { 
     "price": 51, 
     "numsc": 2, 
     "name": "this app is about animals", 
     "sc1": "printed-dress.jpg", 
     "sc2": "printed-dress2.jpg" 
    } 
], 
"colors": [ 
    { 
     "color": "#5D9CEC", 
     "name": "blue" 
    }, 
    { 
     "color": "#FCCACD", 
     "name": "pink" 
    } 
] 

}

你能幫助我PLZ?

+0

搜索上_google_ –

+0

這裏一個對象,並在對象一個數組,什麼問題來分析呢? –

回答

1
JSONObject object = new JSONObject(your-string); 

    JSONArray details=object.getJSONArray("details"); 
for(int j=0;j<details.length();j++){ 
     JSONObject detail= details.getJSONObject(i); 
    String price = detail.getString("price"); 
    .... 
    } 
    JSONArray colors = object.getJSONArray("colors"); 

    for(int i=0;i<colors.length();i++){ 
     JSONObject obj= colors.getJSONObject(i); 
     // parse your json here 
    String color = obj.getString("color") 

    } 
+0

「detail」是JSONArray而不是JSONObject。 – Kunu

+0

@Kunu是的,編輯 –

+0

謝謝!它的工作很好。 – user5137770

0

請參見下面的代碼:

private void decodeJSON() 
    { 
     String JSONString = "you json String"; 
     try 
     { 
      JSONObject obj = new JSONObject(JSONString); 
      JSONArray arr = obj.getJSONArray("detail"); 
      JSONObject detail = arr.getJSONObject(0); 
      int price = detail.getInt("price"); // do same thing to get other values 


      arr = obj.getJSONArray("colors"); 
      JSONObject color = arr.getJSONObject(0); 
      String colorValue = color.getString("color"); 
      String name = color.getString("name"); 

      // do same thing for next object in array. 
     } catch (JSONException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    }