Java – Convert ArrayList to JSON – Android

Convert ArrayList to JSON – Android… here is a solution to the problem.

Convert ArrayList to JSON – Android

I have a list of arrays and a separate string. I want to convert them to JSON format and want it to be lower than json format.

Expected format,

{  
"last_sync_date": "2014-06-30 04:47:45",
"recordset": [
    {
        "contact_group": {
            "guid": "y37845y8y",
            "name": "Family",        
            "description": "Family members",              
            "isDeleted": 0        
        } 
    },
    {
        "contact_group": { 
            "guid": "gt45tergh4",        
            "name": "Office",        
            "description": "Office members",              
            "isDeleted": 0        
        } 
    } 
]
} 

I used it this way, but wrong

public void createGroupInServer(Activity activity, String lastSyncDateTime, ArrayList<ContactGroup> groups)
        throws JSONException {

 create json object to contact group
    JSONObject syncDateTime = new JSONObject();
    syncDateTime.putOpt("last_sync_date", lastSyncDateTime);

JSONArray jsArray = new JSONArray("recordset");

for (int i=0; i < groups.size(); i++) {
        JSONObject adsJsonObject = new JSONObject("contact_group");
        adsJsonObject = jsArray.getJSONObject(i);
        adsJsonObject.put("guid", groups.get(i).getGroupId());
        adsJsonObject.put("name", groups.get(i).getGroupName());
        adsJsonObject.put("isDeleted", groups.get(i).getIsDeleted());
}

Please help.

Solution

You’re basically on the right track… But there are some bugs :

public JSONObject createGroupInServer(
        Activity activity, String lastSyncDateTime,
        ArrayList<ContactGroup> groups)
        throws JSONException {

JSONObject jResult = new JSONObject();
    jResult.putOpt("last_sync_date", lastSyncDateTime);

JSONArray jArray = new JSONArray();

for (int i = 0; i < groups.size(); i++) {
        JSONObject jGroup = new JSONObject();
        jGroup.put("guid", groups.get(i).getGroupId());
        jGroup.put("name", groups.get(i).getGroupName());
        jGroup.put("isDeleted", groups.get(i).getIsDeleted());
         etcetera

JSONObject jOuter = new JSONObject();
        jOuter.put("contact_group", jGroup);

jArray.put(jOuter);
    }

jResult.put("recordset", jArray);
    return jResult;
}

But I agree with other answers that suggest that you use a “mapping” technique like GSON instead of hand-coding. Especially if this becomes more complicated.

Related Problems and Solutions