小编典典

在Android中解析JSON对象

json

我有JSON对象,如下所示:

[
    {
        "Project": {
            "id": "1",
            "project_name": "name"
        },
        "AllocationDetail": [
            {
                "id": "1",
                "project_id": "1",
                "team_name": "ror",
                "week_percentage_work": "50",
                "in_today": "1",
                "actual_hours": "30",
                "remaining_hours": "100",
                "time_difference": null,
                "created": "2012-01-13 15:48:33",
                "modified": "2012-01-13 15:48:33"
            },
            {
                "id": "2",
                "project_id": "1",
                "team_name": "php",
                "week_percentage_work": "40",
                "in_today": "2",
                "actual_hours": "50",
                "remaining_hours": "100",
                "time_difference": null,
                "created": "2012-01-13 15:49:40",
                "modified": "2012-01-13 15:49:40"
            }
        ]
    }
]

我想在android中解析数据并将其存储到数据库中,但是我在Jsonobject中感到困惑,谢谢


阅读 209

收藏
2020-07-27

共1个答案

小编典典

以下是用于解析json字符串的代码段代码。请经历一下:

    String response = <Your JSON String>;
            String Project = null;
            String AllocationDetail = null;
            try {
                JSONArray menuObject = new JSONArray(response);
                 for (int i = 0; i< menuObject.length(); i++) {
                        Project     =   menuObject.getJSONObject(i).getString("Project").toString();
                        System.out.println("Project="+Project);
                        AllocationDetail    =   menuObject.getJSONObject(i).getString("AllocationDetail").toString();
                        System.out.println("AllocationDetail="+AllocationDetail);
                 }
                 JSONObject jsonObject  =   new JSONObject(Project);
                 String id = jsonObject.getString("id");
                 System.out.println("id="+id);
                 String project_name = jsonObject.getString("project_name");
                 System.out.println("project_name="+project_name);

                 JSONArray jArray = new JSONArray(AllocationDetail);
                 for (int i = 0; i< jArray.length(); i++) {
                     String team_name       =   jArray.getJSONObject(i).getString("team_name").toString();
                     System.out.println("team_name="+team_name);
                     String week_percentage_work        =   jArray.getJSONObject(i).getString("week_percentage_work").toString();
                     System.out.println("week_percentage_work="+week_percentage_work);
                 }
            } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
2020-07-27