javaScript中内置了一个JSON对象,可以用来进行json与字符串之间的转换
json转换成字符串:使用JSON.stringify()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| let userArr = [ { userId:1, userName:'张三', userSex:'男' },{ userId:2, userName:'李四', userSex:'女' },{ userId:3, userName:'王五', userSex:'男' } ] let str = JSON.stringify(userArr); console.log(str);
|
字符串转换成json:使用JSON.parse()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| let userArr = [ { userId:1, userName:'张三', userSex:'男' },{ userId:2, userName:'李四', userSex:'女' },{ userId:3, userName:'王五', userSex:'男' } ]
let str = JSON.stringify(userArr); let new_user = JSON.parse(str); console.log(new_user);
|
java对象转化为json格式字符串数据返回到前端页面
JsonModel.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package com.lan.utils;
public class JsonModel<T>{ private int code; private String msg; private long total; private T rows;
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
public long getTotal() { return total; }
public void setTotal(long total) { this.total = total; }
public T getRows() { return rows; }
public void setRows(T rows) { this.rows = rows; } }
|
JsonUtil.java
1 2 3 4 5 6 7 8 9
| package com.lan.utils;
import com.alibaba.fastjson.JSONObject;
public class JsonUtil { public static String toJSONString(Object obj) { return JSONObject.toJSONString(obj); } }
|
controller层返回json数据 —— servlet测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public void allUserInfo(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { List<User> list = userService.SelectAllUserServlet(); JsonModel<List<User>> jsonModel = new JsonModel<>(); if(list==null) { jsonModel.setCode(0); jsonModel.setMsg("error..."); }else { jsonModel.setCode(1); jsonModel.setMsg("success..."); jsonModel.setRows(list); jsonModel.setTotal(list.size());
} response.getWriter().println(JsonUtil.toJSONString(jsonModel.getRows())); }
|