json包下载
- 下载jar包当然是下大厂滴
- 推荐Alibaba的fastjson
- 推荐Google的gjson
- 本文讲fastjson
https://github.com/alibaba/fastjson.git
json的常见格式
- key - value 键值对
{"key":"value"}
- 多个key - value对
{"key1":"value", "key2":"value"}
- Java中的List集合
[{"k1":"v1", "k2":"v2"},{"k1":"v1", "k2":"v2"}]
- Java中的map集合(字典)
{"key1": {"k1":"v1", "k2":"v2"},"key2": {"k1":"v1", "k2":"v2"}}
fast-json包使用–Java中对象转换为json字符串
- 先以学生实体类为demo
package com.lovely.entity;import java.sql.Date;
import java.sql.Timestamp;import com.alibaba.fastjson.annotation.JSONField;public class Student {private Integer id;private String name;private Integer age;@JSONField(format="yyyy-MM-dd")private Date date;@JSONField(format="yyyy-MM-dd HH:mm:ss")private Timestamp time;public Student() {}public Student(Integer id, String name, Integer age, Date date,Timestamp time) {super();this.id = id;this.name = name;this.age = age;this.date = date;this.time = time;}public Integer getId() {return id;}public void setId(Integer 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;}public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public Timestamp getTime() {return time;}public void setTime(Timestamp time) {this.time = time;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", age=" + age+ ", date=" + date + ", time=" + time + "]\n";}}
- 把学生对象,list集合,map集合转换为json字符串
// 对于有日期的在属性上加上注解!上面加了。static Student stu1 = new Student(1, "rye", 20, new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()));static Student stu2 = new Student(2, "bitQian", 19, new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()));/*** 对象转换为json字符串 (有时间 日期的 加上@JSONField(format="yyyy-MM-dd") 注解)* {"key1":"value", "key2":"value"}*/static void objToJson1() {// 对于日期的转型 字段要添加注解Object json = JSON.toJSONString(stu1, true);System.out.println(json);}/*** 集合转成json字符串* [* {"k1":"v1", "k2":"v2"},* {"k1":"v1", "k2":"v2"}* ]*/static String arrToJson2() {List<Student> list = new ArrayList<Student>();list.add(stu1);list.add(stu2);String json = JSON.toJSONString(list, true);System.out.println(json);return json;}/*** map集合转换为json字符串* {* "key1": {"k1":"v1", "k2":"v2"},* "key2": {"k1":"v1", "k2":"v2"}* }*/static String mapToJson3() {Map<String, Student> map = new LinkedHashMap<>();map.put("stu1", stu1);map.put("stu2", stu2);String json = JSON.toJSONString(map, true);System.out.println(json);return json;}
- json字符串转换为对象
// 返序列化 把json字符串->student对象/集合对象/map字典对象static void jsonToObj1() {String json = JSON.toJSONString(stu1);Student obj = JSON.parseObject(json, Student.class);// 重写了student toString()System.out.println(obj);}static void jsonToArr2() {String json = arrToJson2();List<Student> list = JSON.parseArray(json, Student.class);System.out.println(list);}static void jsonToMap3() {String json = mapToJson3();Map<?, ?> map = JSON.parseObject(json, Map.class);System.out.println(map); }
- 测试map的json格式转换为map集合
public class Test1 {public static void main(String[] args) {// objToJson1();// arrToJson2();// mapToJson3();// jsonToObj1();// jsonToArr2();jsonToMap3();}}
{"stu1":{"age":20,"date":"2020-07-10","id":1,"name":"rye","time":"2020-07-10 21:13:31"},"stu2":{"age":19,"date":"2020-07-10","id":2,"name":"bitQian","time":"2020-07-10 21:13:31"}
}
{stu1={"id":1,"time":"2020-07-10 21:13:31","name":"rye","age":20,"date":"2020-07-10"}, stu2={"id":2,"time":"2020-07-10 21:13:31","name":"bitQian","age":19,"date":"2020-07-10"}}
Ajax请求servlet,以json作为数据格式交互
- 后台servlet
package com.lovely.servlet;import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.alibaba.fastjson.JSON;
import com.lovely.entity.Student;public class LoadDataServlet extends HttpServlet {/*** @author echo lovely* */private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String stuJson = "";/***三种json(object list map)对象的取值 */String msg = req.getParameter("msg");Student stu1 = new Student();stu1.setId(1);stu1.setName("rye");stu1.setAge(20);Student stu2 = new Student();stu2.setId(2);stu2.setName("bitQian");stu2.setAge(19); if ("object".equals(msg)) {stuJson = JSON.toJSONString(stu1);} else if ("list".equals(msg)) {ArrayList<Student> list = new ArrayList<Student>();list.add(stu1);list.add(stu2);stuJson = JSON.toJSONString(list);} else if ("map".equals(msg)) {HashMap<String,Student> map = new HashMap<String, Student>();map.put("stu1", stu1);map.put("stu2", stu2);stuJson = JSON.toJSONString(map);}// 响应json格式字符串resp.setContentType("text/json;charset=utf-8");PrintWriter out = resp.getWriter();out.print(stuJson);out.close();}}
- 页面Ajax请求
<html><head><title>My JSP 'list.jsp' starting page</title><script type="text/javascript" src="js/jquery-3.2.1.js"></script><script type="text/javascript"> $(function() { // ready 函数.../*测试三种json(object list map)对象的取值 */$("#btn1").click(function() {$.get("LoadDataServlet",{"msg": "object"},function(data) {console.log(data);console.log(data.id + "\t" + data.name + "\t" + data.age);});});$("#btn2").click(function() {$.get("LoadDataServlet",{"msg": "list"}, function(list) {console.log(list);// 遍历list json数组for (var i = 0; i < list.length; i ++) {console.log(list[i]);}});});$("#btn3").click(function() {$.post("LoadDataServlet",{"msg": "map"},function (data) {console.log(data);for (var stu in data) {console.log(data[stu].id + "\t" + data[stu].name + "\t" + data[stu].age);}});});});</script></head><body><!-- 测试三种json格式字符串 --><input type="button" value="object" id="btn1"/><input type="button" value="list" id="btn2"/><input type="button" value="map" id="btn3"/></body>
</html>
-
单个student对象
-
list集合对象
-
map集合对象
- 更新…