-2

I am creating an app in which i need to parse a list of contacts which is in JSONObject format, with key before each object, i don't know how to parse this format.

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

3 Answers3

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!
}
}
Binesh Kumar
  • 2,763
  • 1
  • 16
  • 23
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();
}

please try this it helps

Zaki Pathan
  • 1,762
  • 1
  • 13
  • 26
0

You can use GSON library to parse it.

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);

Item Class

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;
    }
}

You need to add the following to the build.gradle file,

compile 'com.google.code.gson:gson:2.8.0'
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33