json字符串如何轉爲實體類型

使用fastJson的JSON.parseObject()方法。

String jsonResult = "  ";//json字符串

 System.out.println(jsonResult);//jsonResult是json字符串

Entity result = JSON.parseObject(jsonResult, Entity.class);//把json字符串轉爲實體類

 //result是實體類結果

 

此方法可以使用於前端傳值是json字符串,字符串中的名字和實體類中的字段名稱一致,查詢條件需要實體類作爲參數

例:

@RequestMapping(value = "query.action", produces = "application/json; charset=utf-8")
 @ResponseBody

public String query(Entity  entity ,HttpServletRequest request, HttpServletResponse response){
        String param=request.getParameter("param");
        if(StringUtils.isNotBlank(param)) {
            try {
                param=java.net.URLDecoder.decode(param,"UTF-8");
                entity =JSONObject.parseObject(param, Entity  .class);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    
        }

 List<Entity> list = service.get(entity);
 return JSONObject.toJSONString(list);

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章