文章目录
JSON:
1. 概念: JavaScript Object Notation
JavaScript对象表示法
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
var p = {"name":"张三","age":23,"gender":"男"};
json现在多用于存储和交换文本信息的语法
进行数据的传输
JSON 比 XML 更小、更快,更易解析。
2. 语法:
(1)基本规则
① 数据在名称/值对中:json数据是由键值对构成的
- 键:用引号(单双都行)引起来,也可以不使用引号
- 值:得取值类型:
1.数字(整数或浮点数)
2.字符串(在双引号中)
3.逻辑值(true 或 false)
4.数组(在方括号中){"persons":[{},{}]}
5.对象(在花括号中){"address":{"province":"陕西"....}}
6.null
② 数据由逗号分隔:多个键值对由逗号分隔
③ 花括号保存对象:使用{}定义json 格式
④ 方括号保存数组:[]
<script>
//1.定义基本格式
var person = {"name":"张三",age:23,'gender':true};
//获取name
var personName1 = person.name;
var personName2 = person["name"];
//2.嵌套格式 {} --->[]
var persons = {
"persons1":[//值是数组,数组元素是对象
{"name":"张三",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
],
"persons2":[
{"name":"张三1",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
]
}
// alert(persons.persons1[0].name);
var personsName = persons.persons1[0].name;
//3.嵌套格式 [] ---->{}
var ps = [//定义一个数组,数组元素是json
{"name":"张三1",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
];
var psName = ps[1].name;//李四
</script>
(2) 获取数据:
1.json对象.键名
2. json对象[“键名”]
3. 数组对象[索引]
4. 遍历
<script>
//1.定义基本格式
var person = {"name":"张三",age:23,'gender':true};
//遍历:获取person对象中所有对象
for (var key in person) {
// alert(person[key]);
// alert(person.key);//获取不到,因为key是String
}
//2.嵌套格式 {} --->[]
var persons = {
"persons1":[//值是数组,数组元素是对象
{"name":"张三",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
],
"persons2":[
{"name":"张三1",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
]
}
// alert(persons.persons1[0].name);cc
var personsName = persons.persons1[0].name;
//3.嵌套格式 [] ---->{}
var ps = [//定义一个数组,数组元素是json
{"name":"张三1",age:23,},
{"name":"李四",age:24,},
{"name":"王五",age:25,}
];
//遍历:获取person对象中所有对象
for(var i=0; i<ps.length;i++){
for (var pKey in ps[i]) {
alert(ps[i][pKey]);
}
}
</script>
3. JSON数据和Java对象的相互转换
JSON解析器:常见的解析器:Jsonlib,Gson,fastjson,jackson
(1)JSON转为Java对象
① 导入jackson的相关jar包
② 创建Jackson核心对象 ObjectMapper
③ 调用ObjectMapper的相关方法进行转换
- readValue(json字符串数据,Class)
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
java代码
//演示 JSON字符串转为Java对象
@Test
public void test5() throws Exception {
//1.初始化JSON字符串
String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";
//2.创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//3.转换为Java对象 Person对象
/**
* mapper.readValue(String json,对象.class)方法
* 将json转为java对象
* 结果:Person{name='张三', age=23, gender='男', birthday=null}
*/
Person person = mapper.readValue(json, Person.class);
System.out.println(person);
//Person{name='张三', age=23, gender='男', birthday=null}
}
(2)Java对象转换JSON
① 导入jackson的相关jar包
② 创建Jackson核心对象 ObjectMapper
③ 调用ObjectMapper的相关方法进行转换
转换方法:
① writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
② writeValueAsString(obj):将对象转为json字符串注解:
- @JsonIgnore:排除属性。
- @JsonFormat:属性值得格式化 * @JsonFormat(pattern = “yyyy-MM-dd”)
复杂java对象转换
- List:数组
- Map:对象格式一致
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
java文件
//java对象转JSON字符串
@Test
public void test1() throws Exception {
//1.创建Person
Person p = new Person();
p.setAge(12);
p.setGender("男");
p.setName("张三");
//2.创建Jackson的核心
// 对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3.转换
/**
* 转换方法:
* writeValue(参数1,obj)
* 参数1:
* File:将obj对象转为JSON字符串,并保存到指定的文件中、
* Write:将obj对象转为JSON字符串,并将json数据填充到字符输出流中
* OutputStream:将obj对象转为JSON字符串,并将json数据填充到字节输出流中。。
*
* writeValueAsString(obj):将obj对象转为JSON字符串
*
*/
String json = mapper.writeValueAsString(p);
//System.out.println(json);//{"name":"张三","age":12,"gender":"男"}
//writeValue,将数据写到d://json.txt文件中
mapper.writeValue(new File("json.txt"),p);
//writeValue.将数据关联到Writer中
mapper.writeValue(new FileWriter("json2.txt"),p);
}
@Test
public void test2() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
//System.out.println(json);//{"name":"张三","age":23,"gender":"男","birthday":1530958029263}
/**
* 日期格式默认转换成一串数字,若不想要日期转JSON,添加
* @JsonIgnore
* private Date birthday;
* 结果:{"name":"张三","age":12,"gender":"男"}
* 日期格式化:
* @JsonFormat(pattern = "yyyy-MM-dd")
* private Date birthday;
* 结果:{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}
*/
System.out.println(json);
//{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}
}
@Test
public void test3() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setName("张三");
p1.setAge(23);
p1.setGender("男");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("张三");
p2.setAge(23);
p2.setGender("男");
p2.setBirthday(new Date());
//创建List集合
List<Person> ps = new ArrayList<Person>();
ps.add(p);ps.add(p1);ps.add(p2);
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(ps);
//[{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},
// {"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},
// {"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}]
System.out.println(json);
}
@Test
public void test4() throws Exception {
//1.创建map对象
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","张三");
map.put("age",23);
map.put("gender","男");
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
//{"name":"张三","age":23,"gender":"男"}
System.out.println(json);//{"gender":"男","name":"张三","age":23}
}
4、案例:校验用户名是否存在(Ajax)
服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
方案一
(1) $.get(type)
:将最后一个参数type指定为"json
"
(2)response.setContentType("text/html;charset=utf-8");
方案二 在服务器端设置MIME类型
response.setContentType("application/json;charset=utf-8");
服务器代码Servlet
package cn.itcast;
import com.fasterxml.jackson.databind.ObjectMapper;
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.HashMap;
import java.util.Map;
@WebServlet("/servletUser")
public class ServletUser extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名
String username = request.getParameter("username");
//2.调用service层判断用户是否存在
/*
期望服务器响应回来的格式是:
{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个!!!",}
{"userExsit":false,"msg":"用户名可用!!!",}
*/
//设置响应的数据格式为json
//方式一:response.setContentType("text/html;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
Map<String ,Object> map = new HashMap<String,Object>();
if ("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用户名太受欢迎,请更换一个!!!");
}else {
//不存在
map.put("userExsit",false);
map.put("msg","用户名可用!!!");
}
//将map转为json,并且传给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//并且传给客户端
mapper.writeValue(response.getWriter(),map);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
//在页面加载完成之后触发
$(function () {
//给username绑定blur事件
$("#username").blur(function () {
//获取输入框的值
var username = $(this).val();
/*
期望服务器响应回来的格式是:
{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个!!!",}
{"userExsit":false,"msg":"此用户名太受欢迎,请更换一个!!!",}
*///发送ajax请求:(参数1:服务器端路径,参数2:传递的参数,参数3:页面响应事件,【参数4:设置接收的json格式】)
$.get("servletUser", {username:username},function(data) {
alert(data)
var span = $("#s_username");
//判断userExsit键的值是否是true
if (data.userExsit) {
//用户名存在
span.css("color", "red");
span.html(data.msg);
} else {
//用户名不存在
span.css("color", "green");
span.html(data.msg);
}
}/*,"json"*/);//$.get("servletUser"
});//$("#username").blur(function () {
});//$(function ()
</script>
</head>
<body>
<form>
姓名:<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username"></span><br>
密码:<input type="password" name="" placeholder="请输入密码"><br>
<input type="submit" value="注册">
</form>
</body>
</html>