Search code examples
androidjsoncustom-lists

How to remove the key name in JsonObject?


I have this JsonObject below :

[
 {"ContactNumber":"+91 98765 12345"},
 {"ContactNumber":"+91 123 456 7890"}
]

Since "ContactNumber" is repeating..If i have 5000 contacts,it will repeat..So I need to remove the key-name "ContactNumber" in jsonObject such that new JsonObject will look like this :

"contacts" : [ 
   "+911234567890",
   "+911234567890",
   "+911234567890",
   "+911234567890",
   "+911234567890"
    ]

Actually i am trying to convert the Custom list to JsonObject ..Here its my code snippet

Gson gson = new Gson();
String data = gson.toJson(reqContacts); // reqContacts is Custom list
JsonArray jsonArray = new JsonParser().parse(data).getAsJsonArray();

Solution

  • Try this.

        try {
            String data = "[{\"ContactNumber\":\"+91 98765 12345\"}, " +
                    "{\"ContactNumber\":\"+91 123 456 7890\"}]";
            JSONArray arr1 = new JSONArray();
            JSONArray arr = new JSONArray(data);
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                arr1.put(obj.getString("ContactNumber"));
            }
            JSONObject result = new JSONObject();
            result.put("contacts", arr1);
            System.out.println(""+result);
        } catch (Exception e) {
            e.printStackTrace();
        }