前端与后端通信通过 json 格式传输数据
json 对象
前端
- POST 方式
- Ajax
contentType
使用默认编码格式application/x-www-form-urlencoded
来传递数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| //当 Ajax 以默认格式 application/x-www-form-urlencoded 上传时,data 数据直接使用 JSON 对象 var user= { "username" : username, "password" : password, "rememberMe":rememberMe }; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, data : user, dataType : 'json', success : function(data) { } });
|
后端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| //【推荐】 @RequestMapping("/jsontest.do") public void test(HttpServletRequest request, HttpServletResponse response){ String loginname = request.getParameter("loginname"); String password = request.getParameter("password"); }
@RequestMapping("/jsontest.do") public void test(String loginname,String password){ }
@RequestMapping("/jsontest.do") public void test(User user){
}
【不推荐】 @RequestMapping("/jsontest.do") public void test(@RequestParam String username, @RequestParam String password){ }
|
优点
- 前端传递数据直接使用 json 对象
- 后端可以直接获取参数,也可自动封装到 User 对象中
复杂 Json 对象
前端
- POST方式
- Ajax
contentType
使用默认编码格式application/x-www-form-urlencoded
来传递数据
包含 json 数组字符串,jsonArr 数据示例:
1 2 3 4
| [ {"datetime":"2021-01-21 10:42:31","userid":"1484970664958314","coordinate":"113.537823,34.794309"}, {"datetime":"2021-01-21 10:43:31","userid":"1484970664958314","coordinate":"113.537826,34.794306"} ]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| mui.ajax(serverurl + 'xxx', { dataType: 'json', type: 'POST', timeout: 5000, data: { userid: userid, points: JSON.stringify(jsonArr) }, success: function(data) { }, error: function(xhr, type, errorThrown) { } });
|
后端
1 2 3 4 5 6 7 8 9 10 11 12
| import com.alibaba.fastjson.JSON;
String userid = request.getParameter("userid"); String points = request.getParameter("points"); List<Point> pointList = JSON.parseArray(points, Point.class);
@Data class Point { private String datetime; private String coordinate; }
|
json 字符串
前端
- POST 方式
- Ajax
contentType
使用编码格式application/json
来传递数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var user= { "username" : username, "password" : password }; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, contentType: "application/json; charset=utf-8", data : JSON.stringify(user), dataType : 'json', success : function(data) { } });
|
后端
必须使用@RequestBody
注解
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
| @RequestMapping("/jsontest") public void test(@RequestBody User user){ String username = user.getUsername(); String password = user.getPassword(); }
方法 2 @RequestMapping("/jsontest") public void test(@RequestBody Map map){ String username = map.get("username").toString(); String password = map.get("password").toString(); }
方法 3 public void test(@RequestBody String jsonData) { JSONObject jsonObject = JSON.parseObject(jsonData); String username= jsonObject.getString("username"); String username= jsonObject.getString("password"); }
方法 4 public void test(@RequestBody JSONObject data) { System.out.println(data.get("username")); System.out.println(data.get("password")); }
|
缺点
- 前端需要使用JSON.stringify()将JSON对象转换为JSON字符串
- 后端在接受参数的时候比较麻烦,没有第1种简单,也没有第一种灵活
简单数组
字符串、数值等数组
前端
- POST 或 PUT方式
- Ajax
contentType
使用编码格式application/json
来传递数据
1 2 3 4 5 6 7 8 9 10 11
| var user = ['admin', 'zhangsan']; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, contentType: "application/json; charset=utf-8", data : JSON.stringify(user), dataType : 'json', success : function(data) { } });
|
后端
必须使用@RequestBody
注解
1 2 3 4 5
| @PutMapping("/jsontest") public void test(@RequestBody String[] user){ }
|
Json 数组
前端
- POST 或 PUT方式
- Ajax
contentType
使用编码格式application/json
来传递数据
1 2 3 4 5 6 7 8 9 10 11 12
| var users = [{name: 'admin', age: 20}, {name: 'zhangsan', age: 30}]; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, contentType: "application/json; charset=utf-8", data : JSON.stringify(users), dataType : 'json', success : function(data) { } });
|
后端
必须使用@RequestBody
注解
1 2 3 4 5 6
|
@PutMapping("/jsontest") public void test(@RequestBody List<User> users){ }
|
读取 JSON 文件
读取数据,转换为Java对象
从 json 文件中读取数据
1 2 3 4 5 6 7
| { "version": "1.2.2", "apkfilename": "scmapp.apk", "wgtfilename": "scmapp.wgt", "updateapk": false, "gpsuploadbatch": 1 }
|
使用 fastjson 实现 json字符串转换为 Java 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import com.alibaba.fastjson.JSON; import lombok.Data; import org.apache.commons.io.IOUtils;
InputStream inputStream = null; try { inputStream = new FileInputStream(Constants.PRO_REAL_PATH + "/app/version.json"); String version = IOUtils.toString(inputStream, "utf8"); return JSON.parseObject(version, AppVersion.class); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
@Data class AppVersion { private String version; private String apkfilename; private String wgtfilename; private Boolean updateapk; private int gpsuploadbatch; }
|
JSON 字符串与对象转换
举例:var str = ‘{“name”:”小明”,”age”:18}’;
将字符串转化 json 对象的 3 种方式
1 2 3
| 1. var json = JSON.parse(str); 2. var json = eval("(" + str + ")"); 3. var json = (new Function("return " + str))();
|
坑:
- key 不加双引号,如
str = '{name:"小明",age:18}';
- 错用双引号套单引号,如
var str = "{'name':' 小明 ', 'age':18}";
兼容问题
IE6/7 浏览器中不支持使用 JSON.parse () 方法转成 json 对象,所以需要引入一个 json2.js 文件。可以在这个网站(https://github.com/douglascro...)去下载对象文件。
最后总结来说,如果使用 JSON.parse () 方法来转化成 json 对象的数据格式的话,需要注意的是被转化的字符串里面的属性要使用引号,并且总体是单引号套双引号的方式,以及 IE6/7 浏览器是不支持该方法。
当然,如果你使用 eval () 或者 new Function () 的方式来转化,不存在这个问题