JavaWeb——json基础总结
程序员文章站
2024-02-04 13:40:52
...
一、概述
1、JavaScript Object Notation(JSON) :JavaScript对象表示法
2、代码
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
var p = {"name":"张三","age":23,"gender":"男"};
3、作用
- json现在多用于存储和交换文本信息的语法
- 进行数据的传输
- JSON 比 XML 更小、更快,更易解析
二、json 语法
1、基本规则
- 数据在名称/值对中:json数据是由键值对构成的
- 键用引号(单双都行)引起来,也可以不使用引号
- 数据由逗号分隔:多个键值对由逗号分隔
- 花括号保存对象:使用
{}
定义json 格式 - 方括号保存数组:
[]
2、值的取值类型
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 数组(在方括号中)
{"persons":[{},{}]}
- 对象(在花括号中)
{"address":{"province":"陕西"....}}
- null
3、json 的遍历
//1.定义基本格式
var person = {"name": "张三", age: 23, 'gender': true};
var ps = [{"name": "张三", "age": 23, "gender": true},
{"name": "李四", "age": 24, "gender": true},
{"name": "王五", "age": 25, "gender": false}];
//获取person对象中所有的键和值
//for in 循环
/* for(var key in person){
//这样的方式获取不行。因为相当于 person."name"
//alert(key + ":" + person.key);
alert(key+":"+person[key]);
}*/
//获取ps中的所有值
for (var i = 0; i < ps.length; i++) {
var p = ps[i];
for(var key in p){
alert(key+":"+p[key]);
}
}
三、json数据转换为Java对象
1、JSON常见的解析器:
- Jsonlib(Apache、已淘汰)
- Gson(谷歌、已淘汰)
- fastjson(简单)
- jackson(常用)
2、JSON转为Java对象
- 导入jackson的相关jar包
- 创建Jackson核心对象 ObjectMapper
- 调用ObjectMapper的相关方法进行转换
- readValue(json字符串数据,Class)
四、Java对象转换为json数据
1、使用步骤:
- 导入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:对象格式一致
- 转换方法:
2、代码
封装一个实体类 Person.java
package cn.lemon.domain;
import java.util.Date;
public class Person {
private String name;
private int age ;
private String gender;
// @JsonIgnore
// @JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
新建一个测试类 JsonTest.java
package cn.lemon.json;
import java.io.FileWriter;
import java.util.*;
import cn.lemon.domain.Person;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTest {
//Java对象转为JSON字符串
@Test
public void test1() throws Exception {
//1.创建Person对象
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");
//2.创建Jackson的核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3.转换
/*
转换方法:
writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
writeValueAsString(obj):将对象转为json字符串
*/
String json = mapper.writeValueAsString(p);
System.out.println(json);
//{"name":"张三","age":23,"gender":"男"}
//System.out.println(json);//{"name":"张三","age":23,"gender":"男"}
//writeValue,将数据写到d://a.txt文件中
//mapper.writeValue(new File("d://a.txt"),p);
//writeValue.将数据关联到Writer中
mapper.writeValue(new FileWriter("d://b.txt"),p);
}
/**
* 转换json时对于时间的处理
* @throws Exception
*/
@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}
//{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}
}
/**
* 转换json集合
* @throws Exception
*/
@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);
}
/**
* map转换json
* @throws Exception
*/
@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","男");
map.put("location","北京");
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
//{"name":"张三","age":23,"gender":"男"}
System.out.println(json);//{"gender":"男","name":"张三","age":23}
}
//演示 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对象
Person person = mapper.readValue(json, Person.class);
System.out.println(person);
}
}
五、案例——效验用户名
服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
-
$.get(type)
:将最后一个参数type指定为"json" - 在服务器端设置MIME类型
response.setContentType("application/json;charset=utf-8");
新建 regist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册表单</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(function(){
$("#username").blur(function(){//离开焦点事件
$.post("/project/servletDemo", {"username": $("#username").val()}, function(o){
if (o.flag) {
$("#s_username").css("color", "red");
} else {
$("#s_username").css("color", "black");
}
$("#s_username").html(o.msg);
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username"></span>
<br>
<input type="password" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册"><br>
</form>
</body>
</html>
新建 ServletDemo.java
package cn.lemon.servlet;
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("/servletDemo")
public class ServletDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");//设置响应数据的格式为 json
String username = request.getParameter("username");//获取用户名
Map<String, Object> result = new HashMap<>();
if ("tomcat".equals(username)) {
result.put("msg", "用户名已存在");
result.put("flag", true);
} else {
result.put("msg", "用户名可以使用");
result.put("flag", false);
}
ObjectMapper objectMapper = new ObjectMapper();//将 map 转换为 json
objectMapper.writeValue(response.getWriter(), result);//把数据传递给客户端
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
上一篇: JavaWeb篇-Json&Ajax
下一篇: 自己的php学习笔记(部分)