json與物件之間的相互轉換
阿新 • • 發佈:2018-12-17
1,將實體類的每個屬性以鍵值對的形式發到map中
ErrorCode code =new ErrorCode(1, "SUCCESS"); JSONObject json=JSONObject.fromObject(code); Map<String, String> map = new HashMap<String, String>(); map.putAll(json); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); System.out.println("key=" + key + " value=" + value); }
2,將json字串轉為實體類物件
@org.junit.Test public void test4(){ GetCardNoInHospitalResp respdata=new GetCardNoInHospitalResp(); String response="{'message':'SUCCESS','data':{'cardNo':'12345','code':0,'message':''},'code':'0'}"; JSONObject json = JSONObject.fromObject(response); JSONObject data=(JSONObject) json.get("data"); respdata=com.alibaba.fastjson.JSONObject.parseObject(data.toString(), GetCardNoInHospitalResp.class); System.out.println(respdata.getCardNo()); }
3.將實體類轉化為json字串
jsonObject = JSONObject.fromObject("物件");
4.將json字串輸出到頁面
protected void jsonObj(String jobj) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(jobj); } catch (Exception e) { e.printStackTrace(); } }