如何从JSON的密钥获取数据

时间:2017-03-01 12:23:41

标签: android json parsing

我正在创建一个应用程序,我需要解析一个JSONObject格式的联系人列表,在每个对象之前使用密钥,我不知道如何解析这种格式。

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

3 个答案:

答案 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!
}
}

答案 1 :(得分: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();
}

请尝试这帮助

答案 2 :(得分: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'