簡體   English   中英

將ArrayList轉換為JSON - Android

[英]Converting ArrayList to JSON - Android

我有一個數組列表和一個單獨的字符串。 我想將它們轉換為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());
}

請幫忙。

你大部分都走在正確的軌道上......但是有一些錯誤:

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這樣的“映射”技術,而不是手工編寫。 特別是如果這變得更復雜。

你可以使用GSON。

它提供了許多功能,使用起來非常簡單。

看看這些例子。

http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON

http://www.techrepublic.com/blog/software-engineer/use-gson-to-work-with-json-in-your-android-apps/

希望這可以幫助。

解析為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");   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM