❝原文做者:江户小宝 原文连接:https://zhuanlan.zhihu.com/p/62763428java
❞
{ "ID": 1001, "name": "张三", "age": 24 }web
这个数据就是一个Json对象,Json对象的特色以下:json
[
{"ID": 1001, "name": "张三", "age": 24}, {"ID": 1002, "name": "李四", "age": 25}, {"ID": 1003, "name": "王五", "age": 22} ] 复制代码
这个数据就是一个Json对象数组,Json对象数组的特色以下:后端
上面两个是Json的基本形式,结合在一块儿就能够得出其余的数据形式,例如这个:数组
{
"部门名称":"研发部", "部门成员":[ {"ID": 1001, "name": "张三", "age": 24}, {"ID": 1002, "name": "李四", "age": 25}, {"ID": 1003, "name": "王五", "age": 22}], "部门位置":"xx楼21号" } 复制代码
经过这种变形,使得数据的封装具备很大的灵活性。编辑器
Json字符串应知足如下条件:ide
总结:json能够简单的分为基本形式:json对象,json对象数组。两种基本格式组合变形出其余的形式,但其本质仍是json对象或者json对象数组中的一种。json对象或对象数组能够转化为json字符串,使用于不一样的场合。学习
fastjson是阿里巴巴开发的一款专门用于Java开发的包,能够方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。除了这个fastjson之外,还有Google开发的Gson包,其余形式的如net.sf.json包,均可以实现json的转换。flex
2.2 Fastjson使用this
在fastjson包中主要有3个类,JSON,JSONArray,JSONObject
三者之间的关系以下,JSONObject和JSONArray继承JSON
联系上面讲到的json基础知识并对应这三个类,能够发现,JSONObject表明json对象,JSONArray表明json对象数组,JSON表明JSONObject和JSONArray的转化。
JSONObject实现了Map接口,而json对象中的数据都是以"键:值"对形式出现, JSONObject底层操做是由Map实现的。类中主要是get()方法。JSONObject至关于json对象,该类中主要封装了各类get方法,经过"键:值"对中的键来获取其对应的值。
JSONArray的内部是经过List接口中的方法来完成操做的。JSONArray表明json对象数组,json数组对象中存储的是一个个json对象,因此类中的方法主要用于直接操做json对象。好比其中的add(),remove(),containsAll()方法,对应于json对象的添加,删除与判断。 其内部主要由List接口中的对应方法来实现。
跟JSONObject同样,JSONArray里面也有一些get()方法,不过不经常使用,最有用的应该是getJSONObject(int index)方法,该方法用于获取json对象数组中指定位置的JSONObject对象,配合size()方法,可用于遍历json对象数组中的各个对象。 经过以上两个方法,在配合for循环,便可实现json对象数组的遍历。此外JSONArray中也实现了迭代器方法来遍历。 经过遍历获得JSONObject对象,而后再利用JSONObject类中的get()方法,便可实现最终json数据的获取。
JSON类主要是实现转化用的,最后的数据获取,仍是要经过JSONObject和JSONArray来实现。类中的主要是实现json对象,json对象数组,javabean对象,json字符串之间的相互转化。
总结一下fastjson中三个类的用途和方法:
用JSON.parseObject()方法便可将JSon字符串转化为JSON对象,利用JSONObject中的get()方法来获取JSONObject中的相对应的键对应的值
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.jiyong.config.Student; import com.jiyong.config.Teacher; import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Fastjson用法 */ public class FastJsonOper { //json字符串-简单对象型,加\转义 private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}"; //json字符串-数组类型 private static final String JSON_ARRAY_STR = " [{\"studentName\":\"lily\",\"studentAge\":12}," + "{\"studentName\":\"lucy\",\"studentAge\":15}]"; //复杂格式json字符串 private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\"," + "\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}"; // json字符串与JSONObject之间的转换 @Test public void JsonStrToJSONObject(){ JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); System.out.println("StudentName: " + jsonObject.getString("studentName") + "," + "StudentAge: " + jsonObject.getInteger("studentAge")); } } 复制代码
用JSON.toJSONString()方法便可将JSON对象转化为JSON字符串
/** * 将JSONObject转换为JSON字符串,用JSON.toJSONString()方法便可将JSON字符串转化为JSON对象 */ @Test public void JSONObjectToJSONString(){ JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); String s = JSON.toJSONString(jsonObject); System.out.println(s); } 复制代码
将JSON字符串数组转化为JSONArray,经过JSON的parseArray()方法。JSONArray本质上仍是一个数组,对其进行遍历取得其中的JSONObject,而后再利用JSONObject的get()方法取得其中的值。有两种方式进行遍历
/** * 将JSON字符串数组转化为JSONArray,经过JSON的parseArray()方法 */ @Test public void JSONArrayToJSONStr(){ JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); /** * JSONArray本质上仍是一个数组,对其进行遍历取得其中的JSONObject,而后再利用JSONObject的get()方法取得其中的值 * 方式一是经过jsonArray.size()获取JSONArray中元素的个数, * 再经过getJSONObject(index)获取相应位置的JSONObject,在利用JSONObject的get()进行取值 * 方式二是经过jsonArray.iterator()获取迭代器 * */ // 遍历方式一 // int size = jsonArray.size(); // for(int i = 0;i < size;i++){ // JSONObject jsonObject = jsonArray.getJSONObject(i); // System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge")); // } // 遍历方式二 Iterator<Object> iterator = jsonArray.iterator(); while (iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge")); } } 复制代码
用JSON.toJSONString()方法便可将JSONArray转化为JSON字符串
/** * JSONArray到json字符串-数组类型的转换 */ @Test public void JSONArrayToJSONString(){ JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); String s = JSON.toJSONString(jsonArray); System.out.println(s); } 复制代码
将复杂JSON格式字符串转换为JSONObject,也是经过JSON.parseObject()
/** * 将复杂JSON格式字符串转换为JSONObject,也是经过JSON.parseObject(),能够取其中的部分 */ @Test public void JSONStringTOJSONObject(){ JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR); // 获取简单对象 String teacherName = jsonObject.getString("teacherName"); Integer teacherAge = jsonObject.getInteger("teacherAge"); System.out.println("teacherName: " + teacherName + ",teacherAge " + teacherAge); // 获取JSONObject对象 JSONObject course = jsonObject.getJSONObject("course"); // 获取JSONObject中的数据 String courseName = course.getString("courseName"); Integer code = course.getInteger("code"); System.out.println("courseName: " + courseName + " code: " + code); // 获取JSONArray对象 JSONArray students = jsonObject.getJSONArray("students"); // 获取JSONArray的中的数据 Iterator<Object> iterator = students.iterator(); while (iterator.hasNext()){ JSONObject jsonObject1 = (JSONObject) iterator.next(); System.out.println("studentName: " + jsonObject1.getString("studentName") + ",StudentAge: " + jsonObject1.getInteger("studentAge")); } } 复制代码
用JSON.toJSONString()方法便可将复杂JSONObject转化为JSON字符串
/** * 复杂JSONObject到json字符串的转换 */ @Test public void JSONObjectTOJSON(){ JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR); String s = JSON.toJSONString(jsonObject); System.out.println(s); } 复制代码
定义JavaBean类
package com.fastjson;
public class Student { private String studentName; private int studentAge; public Student() { } public Student(String studentName, int studentAge) { this.studentName = studentName; this.studentAge = studentAge; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getStudentAge() { return studentAge; } public void setStudentAge(int studentAge) { this.studentAge = studentAge; } @Override public String toString() { return "Student{" + "studentName='" + studentName + '\'' + ", studentAge=" + studentAge + '}'; } } package com.jiyong.config; /** * 对于复杂嵌套的JSON格式,利用JavaBean进行转换的时候要注意 * 一、有几个JSONObject就定义几个JavaBean * 二、内层的JSONObject对应的JavaBean做为外层JSONObject对应的JavaBean的一个属性 * 三、解析方法有两种 * 第一种方式,使用TypeReference<T>类 * Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {}) * 第二种方式,使用Gson思想 * Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, Teacher.class); */ import java.util.List; public class Teacher { private String teacherName; private int teacherAge; private Course course; private List<Student> students; public Teacher() { } public Teacher(String teacherName, int teacherAge, Course course, List<Student> students) { this.teacherName = teacherName; this.teacherAge = teacherAge; this.course = course; this.students = students; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTeacherAge() { return teacherAge; } public void setTeacherAge(int teacherAge) { this.teacherAge = teacherAge; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } @Override public String toString() { return "Teacher{" + "teacherName='" + teacherName + '\'' + ", teacherAge=" + teacherAge + ", course=" + course + ", students=" + students + '}'; } } package com.jiyong.config; public class Course { private String courseName; private int code; public Course() { } public Course(String courseName, int code) { this.courseName = courseName; this.code = code; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } @Override public String toString() { return "Course{" + "courseName='" + courseName + '\'' + ", code=" + code + '}'; } } 复制代码
Jason字符串转换为JavaBean有三种方式,推荐经过反射的方式。
/** * json字符串-简单对象到JavaBean之间的转换 * 一、定义JavaBean对象 * 二、Jason字符串转换为JavaBean有三种方式,推荐经过反射的方式 */ @Test public void JSONStringToJavaBeanObj(){ // 第一种方式 JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); String studentName = jsonObject.getString("studentName"); Integer studentAge = jsonObject.getInteger("studentAge"); Student student = new Student(studentName, studentAge); //第二种方式,使用TypeReference<T>类,因为其构造方法使用protected进行修饰,故建立其子类 Student student1 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {}); // 第三种方式,经过反射,建议这种方式 Student student2 = JSON.parseObject(JSON_OBJ_STR, Student.class); } 复制代码
也是经过JSON的toJSONString,不论是JSONObject、JSONArray仍是JavaBean转为为JSON字符串都是经过JSON的toJSONString方法。
/** * JavaBean转换为Json字符串,也是经过JSON的toJSONString,不论是JSONObject、JSONArray仍是JavaBean转为为JSON字符串都是经过JSON的toJSONString方法 */ @Test public void JavaBeanToJsonString(){ Student lily = new Student("lily", 12); String s = JSON.toJSONString(lily); System.out.println(s); } 复制代码
/** * json字符串-数组类型到JavaBean_List的转换 */ @Test public void JSONStrToJavaBeanList(){ // 方式一: JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); //遍历JSONArray List<Student> students = new ArrayList<Student>(); Iterator<Object> iterator = jsonArray.iterator(); while (iterator.hasNext()){ JSONObject next = (JSONObject) iterator.next(); String studentName = next.getString("studentName"); Integer studentAge = next.getInteger("studentAge"); Student student = new Student(studentName, studentAge); students.add(student); } // 方式二,使用TypeReference<T>类,因为其构造方法使用protected进行修饰,故建立其子类 List<Student> studentList = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {}); // 方式三,使用反射 List<Student> students1 = JSON.parseArray(JSON_ARRAY_STR, Student.class); System.out.println(students1); } 复制代码
/** * JavaBean_List到json字符串-数组类型的转换,直接调用JSON.toJSONString()方法便可 */ @Test public void JavaBeanListToJSONStr(){ Student student = new Student("lily", 12); Student student1 = new Student("lucy", 13); List<Student> students = new ArrayList<Student>(); students.add(student); students.add(student1); String s = JSON.toJSONString(student); System.out.println(s); } 复制代码
对于复杂嵌套的JSON格式,利用JavaBean进行转换的时候要注意:
/** * 复杂json格式字符串到JavaBean_obj的转换 */ @Test public void ComplexJsonStrToJavaBean(){ //第一种方式,使用TypeReference<T>类,因为其构造方法使用protected进行修饰,故建立其子类 Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {}); // 第二种方式,使用反射 Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class); } 复制代码
/** * 复杂JavaBean_obj到json格式字符串的转换 */ @Test public void JavaBeanToComplexJSONStr(){ Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class); String s = JSON.toJSONString(teacher); System.out.println(s); } 复制代码
本文使用 mdnice 排版