2017-03-01 63 views
-3

我創建一個應用程序中,我需要解析的聯繫人列表是在JSONObject格式,每一個對象之前鍵表面獲取數據,我不知道如何解析這個格式。如何從JSON

{ 
    "1": { 
    "mobileContact": "98562325", 
    "systemContact": "9198562325" 
    }, 
    "3": { 
    "mobileContact": "987563656", 
    "systemContact": "91987563656" 
    }, 
    "4": { 
    "mobileContact": "965632525", 
    "systemContact": "91965632525" 
    }, 
    "6": { 
    "mobileContact": "965436222", 
    "systemContact": "91965436222" 
    } 
} 
+0

,不,這不是重複*如何在Android的JSON解析的數組(不是JSON對象)* ... **鍵是關鍵** – Selvin

+0

它不是重複的,先生,括號前有關鍵..請給我一個辦法 –

回答

1
Use the keys() iterator to iterate over all the properties, and call get() for each. 

Iterator<String> iter = json.keys(); 
while (iter.hasNext()) { 
String key = iter.next(); 
try { 
    Object value = json.get(key); 
} catch (JSONException e) { 
    // Something went wrong! 
} 
} 
0

您可以使用GSON庫來解析它。

String data = "{\n" + 
     " \"1\": {\n" + 
     " \"mobileContact\": \"98562325\",\n" + 
     " \"systemContact\": \"9198562325\"\n" + 
     " },\n" + 
     " \"3\": {\n" + 
     " \"mobileContact\": \"987563656\",\n" + 
     " \"systemContact\": \"91987563656\"\n" + 
     " },\n" + 
     " \"4\": {\n" + 
     " \"mobileContact\": \"965632525\",\n" + 
     " \"systemContact\": \"91965632525\"\n" + 
     " },\n" + 
     " \"6\": {\n" + 
     " \"mobileContact\": \"965436222\",\n" + 
     " \"systemContact\": \"91965436222\"\n" + 
     " }\n" + 
     "}"; 

Map<String, Item> itemMap = new HashMap<>(); 
itemMap = new Gson().fromJson(data, itemMap.getClass()); 
Log.i("data", itemMap); 

項目類

private class Item { 
    String mobileContact; 
    String systemContact; 

    // getters and setters 

    public String getMobileContact() { 
     return mobileContact; 
    } 

    public void setMobileContact(String mobileContact) { 
     this.mobileContact = mobileContact; 
    } 

    public String getSystemContact() { 
     return systemContact; 
    } 

    public void setSystemContact(String systemContact) { 
     this.systemContact = systemContact; 
    } 
} 

您需要添加以下到build.gradle文件,

compile 'com.google.code.gson:gson:2.8.0' 
1
try{ 
    JSONObject json = new JSONObject(jsonRespondeString); 
    Iterator<String> iterator = json.keys(); 
    while (iterator.hasNext()){ 
      String key = iterator.next(); 

       JSONObject object = json.getJSONObject(key); 
       String value1 = object.getString("key1"); 
       String value2 = object.getString("key2"); 
      } 
    } 
catch (JSONException e){ 
     e.printStackTrace(); 
} 

請儘量將它有助於