2015-07-01 57 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

无需转换格式无法解析它。因为你不确定静态索引的总数。 –