1. 程式人生 > >Restful介面接收JSON字串案例實戰

Restful介面接收JSON字串案例實戰

   程式碼實戰編寫:

@RequestMapping(method=RequestMethod.POST,value="/uploadWeightDatas",params={"datas"})
        public void uploadWeightDatas(HttpServletRequest request,HttpServletResponse response)
    {
        String dataType1 = null;
        String deviceID1 = null;
        String collectDate1 = null;
        String dataValue = null;
        JSONObject result = new JSONObject();
        log.info("the begin of uploadWeightDatas...");
        String param = request.getParameter("datas");
        System.out.println("param="+param);
        log.info("data length = "+param.length());
        log.debug("datas:"+param);
        System.out.println(param);
        try {
            JSONObject map = JSONObject.fromObject(param);
            JSONArray ja = map.getJSONArray("data");
            System.out.println("ja.size = "+ja.size());
            
            for(int i=0;i<ja.size();i++)
            {
            System.out.println("ja="+ja);
            dataType1 = ja.getJSONObject(i).getString("dataType");
            if(dataType1 != null | dataType1.equals("dataType")){
            deviceID1 = ja.getJSONObject(i).getString("deviceID");
            collectDate1 = ja.getJSONObject(i).getString("collectDate");
            dataValue = ja.getJSONObject(i).getString("dataValue");
            JSONArray dv = ja.getJSONObject(i).getJSONArray("dataValue");
            
            System.out.println("dv="+dv);
            String mobile = null;
            System.out.println("dv.size="+dv.size());
            for(int j=0;j<dv.size();j++)
            {
                System.out.println(dv.getJSONObject(j));
                mobile = dv.getJSONObject(j).getString("mobile");
            }
    }
            }
}
        catch (Exception e) {
            log.error(e.getMessage());
    }
}

測試方法:

使用者火狐瀏覽器按照restClient外掛,設定如下:

//header set : Content-Type:  application/x-www-form-urlencoded;text/plain;charset=UTF-8

測試結果: