1. 程式人生 > >獲取json陣列資料或單個數據

獲取json陣列資料或單個數據

單個json資料

{“state”,"1"}

獲取值的方法

JSONObject obj = new JSONObject(“放json資料,即{“state”,“1”}”)

string state = obj.getString("state")

state的值就是1

陣列json資料

<string name="json_array">
    {"calendar": 
        {"calendarlist": 
            [ 
            {"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false}, 


            {"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false} 
            ] 
        } 
    }  </string>
解析程式碼:


public void parseJsonArray(String string){
    try {
        JSONObject jsonObject = new JSONObject(string).getJSONObject("calendar");

        JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < jsonArray.length();i ++){
            JSONObject json = (JSONObject) jsonArray.opt(i);
            String calendar_id = json.getString("calendar_id");
            String title = json.getString("title");

            String category_name = json.getString("category_name");
            String showtime = json.getString("showtime");
            String endshowtime = json.getString("endshowtime");
            String allDay = json.getString("allDay");
            sb.append("calendar_id: " + calendar_id + "\n\n" + "title: " + title + "\n\n" + 
                    "category_name: " + category_name + "\n\n" + "showtime: " + showtime + "\n\n" + 
                    "endshowtime: " + endshowtime + "\n\n" + "allDay: " + allDay + "\n\n" + 
                    "-------------------------------------\n\n");
        }
        text.setText(sb.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

}