JSON封裝與解析

servlet端封裝成json格式html

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        DBQueryImpl query = new DBQueryImpl();
        ArrayList<NoticeBean> _list = query.getNotice();<span style="white-space:pre">    </span>//返回一個NoticeBean類
        // 轉爲json格式
        // JSONArray array = JSONArray.fromObject(_list);

        JSONArray array = new JSONArray();
        array.addAll(_list);
        // 打印到網頁上,不要打印方括號

        String str=array.toString();
        
        out.write(str);

        out.flush();
        out.close();
    }

android端解析出來android

private void getJSONString() {
        String urlPath = "http://192.168.1.102:8080/epay_server/QueryNotice";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlPath);
        try {
            InputStream responseStream = client.execute(post).getEntity()
                    .getContent();
            // 記得轉換成gbk編碼
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(responseStream, "UTF-8"));
            String webContentString = bufferedReader.readLine();
            System.out.println("webCont==>" + webContentString);

            // ItemParent item = new Gson().fromJson(webContentString,
            // ItemParent.class);
            // 生成類數組
            NoticeBean[] _notice = new Gson().fromJson(webContentString,<span style="white-space:pre">    </span>//自動解析成NoticeBean類
                    NoticeBean[].class);
            ArrayList<NoticeBean> _list = new ArrayList<NoticeBean>();
            for (NoticeBean noticeBean : _list) {
                _list.add(noticeBean);
            }

//            遍歷list表
            for (int i = 0; i < _notice.length; i++) {
                System.out.println(_notice[i].get_content());
            }
        } catch (Exception e) {
            System.out.println("解析失敗!");
        }
    }
相關文章
相關標籤/搜索