使用Gson解析动态JSON数据并将其存储在Android中的SQlite DB中

时间:2015-12-29 13:35:07

标签: android json sqlite gson parcelable

我在Android应用程序中从服务器获得此JSON响应,我想通过Gson解析此数据,在Json我的响应权限标记中可能包含20-25个数据密钥如1,2,...权限的每个值包含两个由#键分隔的信息我只需显示那些在响应中获得许可的东西。解析的对象类(Pojo或模型类必须Parcelable已实现) 我的应用程序也支持离线功能,因此需要建议在解析时如何在数据库中同时存储数据。

[{
    "permission": {
        "0": "Title#RaqStar",
        "1": "Desc#Reader of Raw Star",
        "3": "Tytpe#Entertainment",
        "4": "Rating#4.5"
    },
    "id": "233",
    "name": "Movie Raw Star"
}, {
    "permission": {
        "0": "Title#RaqStar",
        "3": "Tytpe#Entertainment",
        "4": "Rating#4.5"
    },
    "id": "233",
    "name": "Movie Raw Star"
}, {
    "permission": {
        "1": "Desc#Reader of Raw Star",
        "3": "Tytpe#Entertainment",
        "4": "Rating#4.5"
    },
    "id": "233",
    "name": "Movie Raw Star"
}, {
    "permission": {
        "1": "Desc#Reader of Raw Star",
        "4": "Rating#4.5"
    },
    "id": "233",
    "name": "Movie Raw Star"
}]

1 个答案:

答案 0 :(得分:0)

    //  Whole response array I took as a String "data"
    try {
        JSONArray array = new JSONArray(data);
        for (int i = 0; i < array.length(); i++) {
             responseJSonObj = array.getJSONObject(i);
             System.out.println(
             generateTitleInfoMap(responseJSonObj.
             getJSONObject("permission")));
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


public static HashMap<String, String> generateTitleInfoMap(JSONObject titleInfoMap) {
    try {
        HashMap<String, String> mapdataVal = new HashMap<String, String>();

        if (titleInfoMap.length() > 0) {
            Iterator keys = titleInfoMap.keys();
            while (keys.hasNext()) {
                // loop to get the dynamic key
                String currentDynamicKey = (String) keys.next();
                String[] ar = (titleInfoMap.getString(currentDynamicKey)).split("#");

                mapdataVal.put(ar[0], ar[1]);
            }
        }
        return mapdataVal;
    } catch (JSONException e) {

    }
    return null;
}