什么是Json
Json的语法格式
JSON数据有三种数据格式,分别如下:
注意:
-
JSON数据的key值:字符串类型,必须加双引号 -
JSON数据的value值:任意类型,如果是字符串则必须加双引号 -
三种数据格式举例:
-
对象类型 {
"name":"张三",
"age":34,
"shuaima":false
}
-
数组/集合类型 [
{"name":"zhangsan","age":67,"addr":"上海"},
{"name":"lisi","age":67,"addr":"上海"},
{"name":"wangwu","age":67,"addr":"上海"}
]
-
混合类型: var stu_score = {
"name":"张三",
"scores":[
{"course":"语文","score":100},
{"course":"数学","score":100},
{"course":"英语","score":100}
]
}
Json对象和Json字符串
JSON对象
- JSON指的是JavaScript对象表示法(JavaScript Object Notation)
- JSON格式在语法上与创建 JavaScript 对象代码是相同的。因此可以把JSON看成是JavaScript对象。
Json对象属于严格的JS对象,key都加双引号
JSON字符串
JSON数据格式是一种文本数据,从服务器传递过来的数据有时候可能是以字符串的形式传递过来如下:
我们可以在js中调用JSON对象的parse方法,将JSON字符串转换成JSON对象:
var personJson = JSON.parse(person);
在javascrip中支持把json格式的字符串,转换为JSON对象
var jsonObj = JSON.parse('{"name":"张三","age":13}');
jsonObj = {"name":"张三","age":13}
Json:JSON格式转换
JSON对象与字符串转换
JSON对象与字符串转换的相关函数
Json转换工具介绍
JSON在js中属于对象,但是在java中属于一个json格式的字符串。
前端中,ajax请求需要dataType:json 将后台响应的json字符串,解析成json对象,才能正常使用.所以我们在后台先将数据转换为json字符串,然后前端获取更加方便。
结论:在企业开发中前端和后端之间是利用json实现数据的交互
JSON的转换工具是通过java封装好的一些jar工具包即依赖第三方开源类库,直接将java对象或集合转换成json格式的数据。
常见的jar包有以下几种:
JackSon使用步骤
开发步骤:
-
导入JackSon相关依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
-
创建java对象和集合; -
使用JackSon包中提供的对象映射器类ObjectMapper类,创建该类对象 -
调用类中的方法String writeValueAsString(对象或集合)将对象或集合转换为json字符串
ObjectMapper对象中的方法 | 说明 |
---|
String writeValueAsString(Object o) | 将一个对象转成JSON格式的字符串 |
转换java对象为Json格式
- 将java对象—转换为—JSON对象:
{"id":1,"studentAge":10,"studentName":"张三"}
- 将List集合–转换为–JSON数组:
[
{ "id": 1,"studentAge": 10, "studentName": "张三"},
{"id": 2, "studentAge": 12,"studentName": "李四"}
]
- 将复杂对象–转换为—JSON混合数据类型:
{"code":"1001","stu":{"id":2,"studentName":"李四","studentAge":12}}
Json: JSON转换工具 - Fastjson
Fastjson介绍
fastjson作用
- 将java对象转成json字符串
- 将json字符串转成 java对象
常用API
fastjson API 入口类是com.alibaba.fastjson.JSON ,常用的序列化操作都可以在JSON 类上的静态方法直接完成。
public static final String toJSONString(Object object);
public static final <T> T parseObject(InputStream is, Class<T> clazz);
举例:User user = JSON.parseObject(request.getInputStream(), User.class);
Fastjso工具的应用
导包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
实体类
package com.itheima.sh.a_maven_01;
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
示例1:请求参数是普通字符串和响应数据是JSON字符串
前端代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="请求参数,后端响应都是普通字符串" onclick="send1()"> <br>
</body>
<script src="js/axios-0.18.0.js"></script>
<script>
function send1() {
let url = "/Union01Servlet";
let param = "username=zs&password=123";
axios.post(url,param).then(resp=>{
console.log(resp.data);
})
}
</script>
</html>
后端代码:
package com.itheima.sh.a_maven_01;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/Union01Servlet")
public class Union01Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + "," + password);
User user = new User(username,password);
String jsonString = JSON.toJSONString(user);
System.out.println("jsonString = " + jsonString);
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(jsonString);
}
}
示例2:请求参数为json格式数据
前端代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="请求参数是Json格式" onclick="send2()"> <br>
</body>
<script src="js/axios-0.18.0.js"></script>
<script>
function send2() {
let url = "/Union02Servlet";
let param = {"username" : "ww","password" : "789"};
axios.post(url,param).then(resp=>{
console.log(typeof resp.data);
console.log(resp.data);
})
}
</script>
</html>
后端代码:
package com.itheima.sh.a_maven_01;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/Union02Servlet")
public class Union01Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
User user = JSON.parseObject(request.getInputStream(), User.class);
String jsonString = JSON.toJSONString(user);
System.out.println("jsonString = " + jsonString);
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(jsonString);
}
}
小结
|