2015-07-01 60 views
1

我使用GSON解析。我能夠解析使用JSON arrayName中,但我不希望使用arrayName中的,因爲它不是static.arrayName可以變化,更會從服務器添加。請建議。解析JSON,而不使用數組名

JSON:

{ 
    "cityCode": "", 
    "list": { 
     "one": [ 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      } 
     ], 
     "three": [ 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      }, 
      { 
       "adults": 2 
      } 
     ] 
    } 
} 
+0

您的JSON是非常糟糕的。你應該根據你的要求Json 1st。 –

回答

1

這適用於你的情況。請記住,JSONObject具有列出其所有屬性的keys()方法。你可以看到,迭代器結果是無序的,運行這段代碼並看到結果。

static void parseJson(String json){ 
    try{ 
     JSONObject object = new JSONObject(json); 

     //Get "list" JSONObject 
     JSONObject obj = object.getJSONObject("list"); 
     //Try to get all attributes of that object 
     @SuppressWarnings("unchecked") 
     Iterator<String> iterator = obj.keys(); 
     while (iterator.hasNext()) { 
      String key = iterator.next(); 
      JSONArray arr = obj.getJSONArray(key); 
      int size = arr.length(); 
      for(int i = 0; i < size; i++){ 
       JSONObject o = arr.getJSONObject(i); 
       Log.e("JSON", "=> "+o.getInt("adults")); 
      } 
     } 
    }catch(JSONException e){ 
     e.printStackTrace(); 
    } 
} 
+0

感謝您的代碼,但我使用GSON怎麼能使用JSON POJO來完成 – Dilip

0

您的JSON應該像以下。

{ 
    "cityCode": "", 
    "list":[ 
      { 
       "index":"one" 
       "adults": 2 
      }, 
      { 
       "index":"one" 
       "adults": 2 
      }, 
      { 
       "index":"one" 
       "adults": 2 
      }, 
      { 
       "index":"three" 
       "adults": 2 
      }, 
      { 
       "index":"three" 
       "adults": 2 
      }, 
      { 
       "index":"three" 
       "adults": 2 
      }, 
      { 
       "index":"three" 
       "adults": 2 
      }, 
      { 
       "index":"three" 
       "adults": 2 
      } 
     ] 
} 

與你分享服務器端代碼。

+0

我agrree用U,但我不能改變JSON格式那麼,有沒有可能wihtout使用數組名稱 – Dilip

+0

無需轉換格式無法解析它。因爲你不確定靜態索引的總數。 –