JSON
一. JSON
1 JSON回顾
JavaScript对象文本表示形式(JavaScript Object Notation : js对象简称)
【1】json在js中是一个对象,在java中是字符串
【2】json是目前 前后端数据交互的主要格式之一
【3】json是一种特殊的 js 对象
#json的语法主要有两种:
1. 对象 { }
2. 数组 [ ]
1. 对象类型
{name:value,name:value}
2. 数组类型
[
{name:value,name:value},
{name:value,name:value},
{name:value,name:value}
]
3. 复杂对象
{
name:value,
wives:[{name:value},{},{}],
son:{name:value}
}
#注意:
1. 其中name必须是string类型
json在js中,name的双引号可以省略
2. value必须是以下数据类型之一:
字符串
数字
对象(JSON 对象)
数组
布尔
Null
3. JSON 中的字符串必须用双引号包围。(单引号不行!)
二. Fastjson
1 fastjson引入
需求
在服务器端有如下User对象需要响应给浏览器.
为了方便浏览器解析, 这就要求服务端在响应之前,需要将转成符合Json格式的字符串.
package com.itheima02.json;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
//TODO: 自己采用字符串拼接的方式输出。
public String toJson() {
return "{\"username\":\""+username+"\",\"password\":"+password+"}";
}
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;
}
}
通过拼接字符串的形式,将java对象转换成json格式字符串无疑是非常麻烦的,在开发中我们一般使用转换工具来达到实现.
所谓的转换工具是通过java封装好的一些jar工具包,可以直接将java对象或集合转换成json格式的字符串。
常见的json转换工具
其实这些工具使用起来都差不多, 目前我们学习使用的是Fastjson
2 fastjson 常用 API
fastjson 作用:
- 将java对象转成json字符串==》响应给前端
- 将json字符串 转成 java对象===》接收前端的json数据封装到对象中
常用API
fastjson API 入口类是com.alibaba.fastjson.JSON
,常用的序列化操作都可以在JSON
类上的静态方法直接完成。
public static final String toJSONString(Object object); // 将java中任意对象序列化为JSON文字符串
//下面的两个方法是将页面获取json数据封装到实体类对象中
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON字符串text解析成指定类型JavaBean
public static final <T> T parseObject(InputStream is, Class<T> clazz); // 将从页面获取的字节输入流中的字符数据解析成指定类型JavaBean
举例:User user = JSON.parseObject(request.getInputStream(), User.class);
注意:
1)request.getInputStream():表示获取关联浏览器的字节输入流
2)使用parseObject方法将前端接收的json数据转换为对应实体类对象,要求前端传递的json数据的key必须和实体类对象的成员变量名一致
举例:
{"username":"张子枫","password":1234} 来自于前端浏览器
实体类:
class User{
private String username;//这里的成员变量必须前端提交json格式的数据的key一致,必须是username
private String password;
}
3 fastjson 使用实例
1 导包
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2 实体类
package com.itheima02.json;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
//TODO: 自己采用字符串拼接的方式输出。
public String toJson() {
return "{\"username\":\""+username+"\",\"password\":"+password+"}";
}
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;
}
}
3 测试
/*
TODO 需求:
java对象或集合 转换成 json格式字符串
json格式字符串 转换成 java对象或集合
*/
package com.itheima.test;
import com.alibaba.fastjson.JSON;
import com.itheima02.json.User;
import org.junit.Test;
import java.util.ArrayList;
/*
TODO 需求:
java对象或集合 转换成 json格式字符串
json格式字符串 转换成 java对象或集合
*/
public class JsonDemo {
@Test
public void method01(){
User user = new User("zs", "123");
System.out.println(user.toJson());
}
@Test
public void method02(){
//java对象转json格式字符串
User user = new User("ls", "123");
//{"password":"123","username":"ls"}
String s = JSON.toJSONString(user);
System.out.println(s);
}
@Test
public void method03(){
//java集合转json格式字符串
User user1 = new User("ls", "123");
User user2 = new User("ww", "110");
ArrayList<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
//[{"password":"123","username":"ls"},{"password":"110","username":"ww"}]
String s = JSON.toJSONString(list);
System.out.println(s);
}
@Test
public void method04(){
//json格式字符串转java对象
String json = "{\"password\":\"123\",\"username\":\"ls\"}";
/*
ORM: object relationship mapping 对象关系映射
1. 体现: 一条数据映射成一个java对象
2. 原理: 反射
1). 首先解析json字符串,变成map
2). 然后遍历map
key 对应 value
username ls <-
password 123
3). 反射操作对象
// User类的Class对象
Class clazz = User.class;
// 使用User类的空参构造创建实例
User user = clazz.newInstance();
//获取类中方法
// 方法名的推断: set + map中的key
Method method = clazz.getMethod("setUsername",String.class);
//调用方法 user.setUsername("ls");
method.invoke(user,"ls")
*/
//User{username='ls', password='123'}
User user = JSON.parseObject(json, User.class);
System.out.println(user);
}
}
三. ajax和json综合 (特别重要!!!)
1 请求参数和响应数据都是普通字符串
<template>
<div>
<h1>axios和json综合</h1>
<input type="button" value="请求和响应都是普通字符串" @click="method01()"> <br>
<input type="button" value="响应数据改成json字符串" @click="method02()"> <br>
<input type="button" value="请求数据也改成json字符串" @click="method03()"> <br>
<hr>
<h3>好友列表</h3>
<div id="messageDiv"></div>
<table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<!-- <tr>
<td></td>
<td></td>
<td></td>
</tr>-->
</table>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
//1.请求和响应都是普通字符串
method01(){
let url = "/Union01Servlet";
let param = "username=admin&password=123";
// axios.get(url+"?"+param)
axios.post(url,param).then(response=>{
console.log(response.data);
}).catch(error=>{
console.log(error);
}).finally(()=>{
console.log("无论如何都执行");
})
}
}
}
</script>
<style>
</style>
package com.itheima04.union;
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;
@WebServlet("/Union01Servlet")
public class Union01Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取请求
//解决post请求乱码问题
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + "," + password);
//2. 业务处理
//3. 响应数据
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("响应数据");
}
}
2 响应数据改成json格式
需求:查询当前用户的好友 List
list,转成json格式字符串,最后响应
【1】html页面
<template>
<div>
<h1>axios和json综合</h1>
<input type="button" value="请求和响应都是普通字符串" @click="method01()"> <br>
<input type="button" value="响应数据改成json字符串" @click="method02()"> <br>
<input type="button" value="请求数据也改成json字符串" @click="method03()"> <br>
<hr>
<h3>好友列表</h3>
<div id="messageDiv"></div>
<table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<!-- <tr>
<td></td>
<td></td>
<td></td>
</tr>-->
</table>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
//1.请求和响应都是普通字符串
method01(){
let url = "/Union01Servlet"
let param = "username=admin&password=123"
// axios.get(url+"?"+param)
axios.post(url,param).then(response=>{
console.log(response.data);
}).catch(error=>{
console.log(error);
}).finally(()=>{
console.log("无论如何都执行");
})
},
method02(){
let url = "/Union02Servlet"
let param = "username=admin&password=123"
axios.post(url,param).then(response=>{
console.log(response.data);
var messageDiv = document.getElementById("messageDiv");
var myTable = document.getElementById("myTable");
if(response.data.flag){
//请求成功
messageDiv.innerHTML = response.data.message
let content = ""
for(let i=0;i<response.data.valueData.length;i++) {
let friend = response.data.valueData[i];
content += `<tr>
<td>${friend.id}</td>
<td>${friend.name}</td>
<td>${friend.age}</td>
</tr>`;
}
myTable.innerHTML += content
}else{
//请求失败
messageDiv.innerHTML = response.data.message
}
})
}
}
}
</script>
<style>
</style>
【2】Friend类
package com.itheima04.union.po;
import java.io.Serializable;
public class Friend implements Serializable {
private String id;
private String name;
private Integer age;
public Friend() {
}
public Friend(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
【3】Servlet
服务器响应json格式的MIME类型:"application/json"
package com.itheima03.union;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Friend;
import com.itheima.pojo.Result;
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;
import java.util.Collections;
@WebServlet("/Union02Servlet")
public class Union02Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//1. 获取请求
String username = request.getParameter("username");
String password = request.getParameter("password");
//2. 业务处理
// int i = 1/0; // 模拟数据库崩溃
//查询当前用户的好友 List<Friend> list,转成json格式字符串,最后响应
//用伪数据代替
Friend f1 = new Friend("1001", "张三", 18);
Friend f2 = new Friend("1002", "李四", 19);
Friend f3 = new Friend("1003", "王五", 20);
ArrayList<Friend> list = new ArrayList<>();
Collections.addAll(list,f1,f2,f3);
//3. 响应数据
// response.setContentType("text/html;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
Result result = new Result(true, "获取好友列表成功", list);
//fastjson等工具实现 (java对象或集合 转成 json格式字符串)
String json = JSON.toJSONString(result);
response.getWriter().print(json);
} catch (Exception e) {
response.setContentType("application/json;charset=utf-8");
Result result = new Result(false, "获取好友列表失败");
//fastjson等工具实现 (java对象或集合 转成 json格式字符串)
String json = JSON.toJSONString(result);
response.getWriter().print(json);
}
}
}
【4】响应结果的封装Result类
说明:如果响应失败,上述代码并没有考虑,所以为了代码严谨性,我们需要单独在抽取一个实体类,避免失败情况发生的处理方案
private boolean flag;//执行结果,true为执行成功 false为执行失败
private String message;//返回结果信息
private Object valueData;//返回数据(如果是查询操作则设置,如果是增删改则不设置)
package com.itheima.sh.a_json_01;
public class Result {
private boolean flag;//执行结果,true为执行成功 false为执行失败
private String message;//返回结果信息
private Object valueData;//返回数据(如果是查询操作则设置,如果是增删改则不设置)
public Result() {
}
//失败,或者增删改
public Result(boolean flag, String message){
this.flag = flag;
this.message = message;
}
//成功的查询
public Result(boolean flag, String message, Object valueData) {
this.flag = flag;
this.message = message;
this.valueData = valueData;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getValueData() {
return valueData;
}
public void setValueData(Object valueData) {
this.valueData = valueData;
}
}
3 请求参数改成json格式
<template>
<div>
<h1>axios和json综合</h1>
<input type="button" value="请求和响应都是普通字符串" @click="method01()"> <br>
<input type="button" value="响应数据改成json字符串" @click="method02()"> <br>
<input type="button" value="请求数据也改成json字符串" @click="method03()"> <br>
<hr>
<h3>好友列表</h3>
<div id="messageDiv"></div>
<table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<!-- <tr>
<td></td>
<td></td>
<td></td>
</tr>-->
</table>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
//1.请求和响应都是普通字符串
method01(){
let url = "/Union01Servlet"
let param = "username=admin&password=123"
// axios.get(url+"?"+param)
axios.post(url,param).then(response=>{
console.log(response.data);
}).catch(error=>{
console.log(error);
}).finally(()=>{
console.log("无论如何都执行");
})
},
method02(){
let url = "/Union02Servlet"
let param = "username=admin&password=123"
axios.post(url,param).then(response=>{
console.log(response.data);
var messageDiv = document.getElementById("messageDiv");
var myTable = document.getElementById("myTable");
if(response.data.flag){
//请求成功
messageDiv.innerHTML = response.data.message
let content = ""
for(let i=0;i<response.data.valueData.length;i++) {
let friend = response.data.valueData[i];
content += `<tr>
<td>${friend.id}</td>
<td>${friend.name}</td>
<td>${friend.age}</td>
</tr>`;
}
myTable.innerHTML += content
}else{
//请求失败
messageDiv.innerHTML = response.data.message
}
})
},
method03(){
let url = "/Union03Servlet"
/*
TODO: 请求数据改成json格式字符串
*/
// let param = "username=admin&password=123"
let param = {username : "admin",password : "123"}
axios.post(url,param).then(response=>{
console.log(response.data);
var messageDiv = document.getElementById("messageDiv");
var myTable = document.getElementById("myTable");
if(response.data.flag){
//请求成功
messageDiv.innerHTML = response.data.message
let content = ""
for(let i=0;i<response.data.valueData.length;i++) {
let friend = response.data.valueData[i];
content += `<tr>
<td>${friend.id}</td>
<td>${friend.name}</td>
<td>${friend.age}</td>
</tr>`;
}
myTable.innerHTML += content
}else{
//请求失败
messageDiv.innerHTML = response.data.message
}
})
}
}
}
</script>
<style>
</style>
package com.itheima04.union.vo;
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
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;
}
}
package com.itheima03.union;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Friend;
import com.itheima.pojo.Result;
import com.itheima02.json.User;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@WebServlet("/Union03Servlet")
public class Union03Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
/*
TODO 1. 获取请求
1). 请求参数是传统格式 name=value&name=value
后端获取,用get和post统一获取api即可
String username = request.getParameter("username");
2). 请求参数json格式
是无法通过 统一格式获取的
以post为例, 请求参数在请求体中
*/
// String username = request.getParameter("username");
// String password = request.getParameter("password");
// System.out.println(username + "," + password);
// ServletInputStream is = request.getInputStream();
// User user = JSON.parseObject(is, User.class);
User user = BaseController.getBean(request, User.class);
System.out.println(user);
//2. 业务处理
Friend f1 = new Friend("1001", "张三", 18);
Friend f2 = new Friend("1002", "李四", 19);
Friend f3 = new Friend("1003", "王五", 20);
ArrayList<Friend> list = new ArrayList<>();
Collections.addAll(list,f1,f2,f3);
//3. 响应数据
Result result = new Result(true, "获取好友列表成功", list);
// response.setContentType("application/json;charset=utf-8");
// String json = JSON.toJSONString(result);
// response.getWriter().print(json);
BaseController.printResult(response,result);
} catch (Exception e) {
Result result = new Result(false, "获取好友列表失败");
// response.setContentType("application/json;charset=utf-8");
// String json = JSON.toJSONString(result);
// response.getWriter().print(json);
BaseController.printResult(response,result);
}
}
}
4 抽取BaseController
需求:
1.定义public static
T getBean(HttpServletRequest request,Class clazz)方法将请求格式是json的数据封装到实体类对象中 2.定义 public static void printResult(HttpServletResponse response, Result result)方法,将json数据响应给浏览器
package com.itheima03.union;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import com.itheima02.json.User;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class BaseController {
/**
* post请求参数为json格式的数据 转换成 javaBean
*/
public static <T>T getBean(HttpServletRequest request,Class<T> clazz) throws IOException {
ServletInputStream is = request.getInputStream();
T t = JSON.parseObject(is, clazz);
return t;
}
public static void printResult(HttpServletResponse response, Result result) throws IOException {
response.setContentType("application/json;charset=utf-8");
String json = JSON.toJSONString(result);
response.getWriter().print(json);
}
}
标签:username,Day08,String,补充,json,response,Json,password,public
From: https://www.cnblogs.com/-turing/p/17207928.html