将ArrayList转换为JSON - Android

3
我有一个数组列表和一个独立的字符串。我想将它们转换成JSON格式,并期望以下JSON格式。
期望的格式,
{  
"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        
        } 
    } 
]
} 

我用了这种方式,但是不正确。
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());
}

请帮忙。

你考虑过使用Jackson或GSON来减少bug吗?如果没有,那么你应该考虑一下。上述任务将会很简单。 - Vincent Mimoun-Prat
@ZhenxiaoHao - 不是的。这个问题显然是关于将Java对象转换为JSON。他提供的JSON明显旨在成为示例Java代码生成的内容。 - Stephen C
3个回答

6
您大部分情况下是正确的... 但还有一些错误:
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;
}

但我同意其他答案的建议,建议您使用像GSON这样的“映射”技术,而不是手工编写代码。 特别是如果这变得更加复杂。


2

1
将其解析为JSONArray
JSONArray jsonArray = (JSONArray)new JSONParser().parse(your json string);

针对您的代码

    JSONObject jsonObject = (JSONObject)new JSONParser().parse(your json string);
    JSONArray array = (JSONArray)jsonObject.get("recordset");   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接