❝
The original author: edo small treasure the original link: https://zhuanlan.zhihu.com/p/62763428
❞
JSON format and syntax
1.1 a JSON object
{“ID”: 1001, “name”: “zhang SAN “, “age”: 24}
This data is a Json object, which has the following characteristics:
- The data is in curly braces
- The data is presented as “key: value” pairs (where keys are often presented as strings and values can be strings, numbers, or even other JSON objects)
- Each key: value pair is separated by a comma (the last key: value pair omits the comma)
1.2 JSON Object Array
[
{"ID": 1001."name": "Zhang"."age": 24},
{"ID": 1002."name": "Bill"."age": 25},
{"ID": 1003."name": "Fifty"."age": 22}
]
Copy the code
This data is an array of Json objects. Json object arrays have the following characteristics:
- The data is in square brackets where each data is presented as a JSON object and each two data is separated by commas (the last one does not need a comma)
The two above are the basic forms of Json, which can be combined to produce other data forms, such as this:
{
"Department Name":"R&d Department". "Department member": [ {"ID": 1001."name": "Zhang"."age": 24},
{"ID": 1002."name": "Bill"."age": 25},
{"ID": 1003."name": "Fifty"."age": 22}]. "Department Location":"No. 21, Building XX" } Copy the code
Through this deformation, data encapsulation has great flexibility.
1.3: JSON string
The Json string must meet the following conditions:
- It must be a string, and the data in the various operations that support the string must be in one of the formats, either a JSON object, an array of JSON objects, or a combination of the two basic forms.
Conclusion: JSON can be divided into basic forms: JSON object, JSON object array. The combination of the two basic formats morphs into other forms that are essentially json objects or arrays of JSON objects. Json objects or arrays of objects can be converted to JSON strings for different purposes.
Fastjson introduction
2.1 Fastjson profile
Fastjson is a special package developed by Alibaba for Java development, which can easily realize the conversion between JSON objects and JavaBean objects, JavaBean objects and JSON strings, and realize the conversion between JSON objects and JSON strings. In addition to this Fastjson, there is also a Gson package developed by Google, other forms such as net.sf.json package, can implement JSON conversion.
2.2 Fastjson USES
There are three main classes in the FastJSON package: JSON,JSONArray, and JSONObject
JSONObject and JSONArray inherit JSON
According to the basic knowledge of JSON mentioned above and corresponding to these three classes, it can be found that JSONObject represents JSON object, JSONArray represents JSON object array, and JSON represents the transformation of JSONObject and JSONArray.
2.2.1 Using the JSONObject class
JSONObject implements the Map interface, and the data in the JSON object is in the form of “key: value” pairs. The underlying operations of JSONObject are implemented by Map. The class is dominated by the get() method. JSONObject is equivalent to a JSON object. This class mainly encapsulates various GET methods, and obtains the corresponding values through the keys in the “key: value” pair.
2.2.2 Using the JSONArray class
The internal workings of JSONArray are done through methods in the List interface. JSONArray stands for AN array of JSON objects. Json array objects store json objects, so the methods in the class are mainly used to directly manipulate JSON objects. For example, the add(),remove(), and containsAll() methods correspond to adding, removing, and determining JSON objects. Internally, it is mainly implemented by corresponding methods in the List interface.
Just like JSONObject, JSONArray has some get() methods, but they are not very common. The most useful method is getJSONObject(int index), which is used to get the JSONObject at a specified position in the JSON object array. In conjunction with the size() method, you can use it to traverse objects in an array of JSON objects. Through the above two methods, in conjunction with the for loop, you can realize the traversal of the JSON object array. In addition, JSONArray implements iterator methods for traversal. The JSONObject object is obtained through traversal, and then the JSONObject class get() method can be used to achieve the final JSON data acquisition.
2.2.3 Using the JSON class
JSON class is mainly used to achieve transformation, the final data acquisition, or through JSONObject and JSONArray to achieve. Class is mainly to achieve json objects, JSON object array, Javabean objects, JSON string between the mutual conversion.
To summarize the purposes and methods of the three fastjson classes:
- JSONObject: Parses a Json object to get its value, usually using the get() method of the class
- JSONArray: An array of JSON objects, usually obtained by iterators and evaluated by JSONObeject’s get() method.
- JSON: Mainly to achieve JSON objects, JSON object array, Javabean objects, JSON string between the mutual conversion. After the conversion, the values are evaluated in their own way.
JSON case
3.1 JSON String – JSONObject
Use json.parseObject () to convert the JSON string into a JSON object, and use the get() method in JSONObject to obtain the corresponding value of the corresponding key in 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 USES* / public class FastJsonOper { //json string - simple object type, with \ escape private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}"; //json string - Array type private static final String JSON_ARRAY_STR = " [{\"studentName\":\"lily\",\"studentAge\":12}," + "{\"studentName\":\"lucy\",\"studentAge\":15}]"; // Complex format JSON string private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\"," + "\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"stude ntAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}"; // Convert json string to JSONObject @Test public void JsonStrToJSONObject(a){ JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); System.out.println("StudentName: " + jsonObject.getString("studentName") + "," + "StudentAge: " + jsonObject.getInteger("studentAge")); } } Copy the code
3.2 JSONObject – JSON Character string
A JSON object can be converted to a JSON string using the json.tojsonString () method
/ * ** Convert a JSONObject to a JSON string, using json.tojsonString () to convert a JSON string to a JSON object* /
@Test
public void JSONObjectToJSONString(a){
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); String s = JSON.toJSONString(jsonObject); System.out.println(s); } Copy the code
3.3 JSON String Array – JSONArray
Convert an array of JSON strings to a JSONArray using JSON’s parseArray() method. A JSONArray is essentially an array that is iterated over to get its JsonObjects, and then used the JSONObject get() method to get its values. There are two ways to traverse
- A: Jsonarray.size () to get the number of elements in the jsonArray, and getJSONObject(index) to get the corresponding position of the JSONObject, The loop variable retrieves the JSONObject in the JSONArray and uses the GET () of the JSONObject to take its value.
- Method 2: Obtain the iterator from jsonarray.iterator ()
/ * ** Convert a JSON string array to a JSONArray using JSON's parseArray() method* /
@Test
public void JSONArrayToJSONStr(a){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); / * ** JSONArray is essentially an array that is iterated over to get the JSONObject and then used to get the value of the JSONObject's get() methodJsonarray.size () = jsonArray.size()* Then getJSONObject(index) to obtain the corresponding position of the JSONObject, using the JSONObject get() valueIterator (jsonArray.iterator() * * / // traversal mode 1 // 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")); // } // run the following command Iterator<Object> iterator = jsonArray.iterator(); while (iterator.hasNext()){ JSONObject jsonObject = (JSONObject) iterator.next(); System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge")); } } Copy the code
3.4 JSONArray – Json Character string
To convert a JSONArray to a JSON string, use the json.tojsonString () method
/ * ** JSONArray to JSON string - array type conversion* /
@Test
public void JSONArrayToJSONString(a){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); String s = JSON.toJSONString(jsonArray); System.out.println(s); } Copy the code
3.5 Complex JSON String – JSONObject
Convert complex JSON-formatted strings to JSONObject, also via json.parseObject ()
/ * ** Convert complex JSON-formatted strings to JSONObject, also via json.parseObject (), which can be retrieved* /
@Test
public void JSONStringTOJSONObject(a){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR); // Get a simple object String teacherName = jsonObject.getString("teacherName"); Integer teacherAge = jsonObject.getInteger("teacherAge"); System.out.println("teacherName: " + teacherName + ",teacherAge " + teacherAge); // Get the JSONObject JSONObject course = jsonObject.getJSONObject("course"); // Get the data in JSONObject String courseName = course.getString("courseName"); Integer code = course.getInteger("code"); System.out.println("courseName: " + courseName + " code: " + code); // Get the JSONArray object JSONArray students = jsonObject.getJSONArray("students"); // Get the data in the 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")); } } Copy the code
3.6 Complex JSONObject – JSON string
A complex JSONObject can be converted to a JSON string using the json.tojsonString () method
/ * ** Complex JSONObject to JSON string conversion* /
@Test
public void JSONObjectTOJSON(a){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR); String s = JSON.toJSONString(jsonObject); System.out.println(s); } Copy the code
3.7 JSON String – JavaBean
Define the JavaBean classes
package com.fastjson;
public class Student {
private String studentName;
private int studentAge;
public Student(a) {
} public Student(String studentName, int studentAge) { this.studentName = studentName; this.studentAge = studentAge; } public String getStudentName(a) { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getStudentAge(a) { return studentAge; } public void setStudentAge(int studentAge) { this.studentAge = studentAge; } @Override public String toString(a) { return "Student{" + "studentName='" + studentName + '\' ' + ", studentAge=" + studentAge + '} '; } } package com.jiyong.config; / * ** Be careful when converting complex nested JSON formats using Javabeans* 1, there are several JsonObjects to define a few Javabeans* 2, the inner JSONObject corresponding JavaBean as an attribute of the outer JSONObject corresponding JavaBean* 3. There are two methods of parsing* First, use the TypeReference<T> class * Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {}) * The second way is to use the Gson idea * 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(a) { } 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(a) { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTeacherAge(a) { return teacherAge; } public void setTeacherAge(int teacherAge) { this.teacherAge = teacherAge; } public Course getCourse(a) { return course; } public void setCourse(Course course) { this.course = course; } public List<Student> getStudents(a) { return students; } public void setStudents(List<Student> students) { this.students = students; } @Override public String toString(a) { 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(a) { } public Course(String courseName, int code) { this.courseName = courseName; this.code = code; } public String getCourseName(a) { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public int getCode(a) { return code; } public void setCode(int code) { this.code = code; } @Override public String toString(a) { return "Course{" + "courseName='" + courseName + '\' ' + ", code=" + code + '} '; } } Copy the code
There are three ways to convert Jason strings into Javabeans, and reflection is recommended.
/ * ** JSON strings - Conversion between simple objects and Javabeans* 1. Define JavaBean objects* 2. There are three ways to convert Jason strings into Javabeans* /
@Test public void JSONStringToJavaBeanObj(a){ // The first way JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); String studentName = jsonObject.getString("studentName"); Integer studentAge = jsonObject.getInteger("studentAge"); Student student = new Student(studentName, studentAge); // The second way is to use the TypeReference
class, which is subclassed because its constructor is protected
Student student1 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {}); // The third way, by reflection, suggests this way Student student2 = JSON.parseObject(JSON_OBJ_STR, Student.class); } Copy the code
3.8 JavaBean – JSON character string
JSON toJSONString is also used to convert jsonObjects, JsonArrays, and Javabeans into JSON strings.
/ * ** Javabeans are converted to Json strings via Json's toJSONString. JSONObject, JSONArray, and Javabeans are converted to Json strings via Json's toJSONString method* /
@Test
public void JavaBeanToJsonString(a){
Student lily = new Student("lily".12); String s = JSON.toJSONString(lily); System.out.println(s); } Copy the code
3.8 JSON String Array – javabean-list
/ * ** JSON string - Array type conversion to JavaBean_List* /
@Test
public void JSONStrToJavaBeanList(a){
// Method 1: JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); / / traverse 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); } // Use the TypeReference
class and subclass it because its constructor is protected
List<Student> studentList = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {}); // Use reflection List<Student> students1 = JSON.parseArray(JSON_ARRAY_STR, Student.class); System.out.println(students1); } Copy the code
3.10 Javabean-list – JSON string array
/ * *
* JavaBean_List converts toJSON string-array types by calling json.tojsonString ()
* /
@Test public void JavaBeanListToJSONStr(a){ 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); } Copy the code
3.11 Complex Nested JSON String – JavaBean_obj
When converting complex nested JSON formats using Javabeans, note:
- There are several JsonObjects that define several JsonObjects inside javabeans
- The corresponding JavaBean is an attribute of the corresponding JavaBean of the outer JSONObject
/ * ** Complex JSON-formatted string conversion to JavaBean_obj* /
@Test
public void ComplexJsonStrToJavaBean(a){
// First, use the TypeReference
class and subclass it because its constructor is protected
Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {}); // The second way, use reflection Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class); } Copy the code
3.12 JavaBean_obj – A string in complex JSON format
/ * ** Complex JavaBean_obj to JSON format string conversion* /
@Test
public void JavaBeanToComplexJSONStr(a){
Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class); String s = JSON.toJSONString(teacher); System.out.println(s); } Copy the code
This article is formatted using MDNICE