preface

The original author of this article Bigsai (with the public number), this article in an easy to understand way to explain their own understanding of JSON, if there are errors or inaccuracies, please give corrections. The article is also included in Erudite Valley.

Json meaning

Before we get started, what is JSON?

  • A: I guess it’s some kind of advanced technology.
  • B: Why does Google Translate translate the word JSON? What is it? Is there a mistake? (Full of confidence)
  • C: I have heard of json, I only know it is a very lightweight storage structure, but I really don’t understand the details (soft)

Json is not a original word, but is actually short for the four-word JavaScript Object Notation, a lightweight text data interchange format that is language independent (using JavaScript syntax to describe objects). Many programming languages support JSON. Json has become the accepted standard for data transfer between servers and Web applications.

Json is born

Question: How did JSON come about?

This problem, first of all, because of the need to transfer data between the Internet application, and a lot of cross-platform application needs to be interactive, can only take the plain text mode of interaction, and XML is a choice, but the XML specification more and more is becoming more and more complex, parsing efficiency is low, many siege lion head all big, see XML might make for a long time also don’t understand.

Then Douglas Crockford, the great master of JavaScript (the father of JavaScript), invented and promoted JSON according to the specification of JavaScript. Json format is simple and easy to use, but also can be transmitted across platforms, and has been widely recognized and spread. As a result, JSON has become more and more popular and is now one of the mainstream technologies.

What is json (B)?

  • A. avaScript object
  • B. Lightweight text data exchange format
  • [C] a language
  • [D]. A framework

Figure out the JSON sibling and see the difference

json VS xml

When it comes to JSON, there is no comparison in XML. No comparison is no harm. Before JSON and its big brother, XML (Extensible Markup Language), we used XML for file data transfer.

First, let’s look at the difference between JSON and XML from the definition:

JSON (JavaScript Object Notation) A lightweight data exchange format with readable features and ease of writing quickly. Data can be exchanged between different platforms. Its language custom has a C – like custom system (C, C ++, Java, etc.). XML (Extensiable Markup Language) is a structured Markup Language that is used to Markup electronic files. It can be used to mark data and define data types. XML is a source Language that allows users to define their own Markup Language.

The emergence of JSON is the full use of THE advantages of XML, so JSON and XML have some of the same advantages:

  • Good readability and clear structure
  • Hierarchical storage (hierarchical nesting)
  • Can transfer data as Ajax
  • Are cross-platform and can be used as a data transfer format

But JSON is better than blue, and it certainly has some features and advantages that XML does not have, such as:

  • The data format is simple, easy to read and write, and the data is compressed, the file is small, easy to transfer.
  • Json is easy to parse, while XML requires looping through the DOM to parse, which is less efficient.
  • The server and client can use JSON directly for easy maintenance. Different clients may parse XML in different ways.
  • Json has become the accepted standard for data transfer between servers and Web applications.

Nevertheless, XML has its own applications:

  • XML format is more rigorous, more readable, easier to expand, can be a good configuration file.
  • Appeared earlier, in various fields have a wide range of applications, with a general epidemic.

Which of the following is incorrect? (B)

  • A. Json files with the same content are generally simpler and smaller than XML.
  • B. Johnson is much more complex to parse than XML.
  • C. Johnson and XML are both cross-platform text transfer formats.
  • D.johnson is short for the JavaScript Object Notation word.

Small translation officer, JSON application

Json is popular because it has a wide range of applications. It mainly includes front-end transmission of unified platform used in combination with Ajax; Cross-platform data transmission; Non-relational database document storage, etc. These areas make applications much more efficient by using JSON.

Front-end Ajax + JSON asynchronous transmission:

Json itself originates from JavaScript, and JavaScript has a natural advantage in parsing JSON, whereas in Ajax asynchronously loaded data, the whole page has already been loaded, and we just need to render the real data in place. The real data of this part is stored with JSON text, and JavaScript is used to asynchronously request to the server. After the request succeeds, JavaScript will render and fill it. Below is a brief description of the traditional way of interacting with the front end and the ajax asynchronous interaction:

If you’re not familiar with AJAX? Process also look not to understand, where also can’t understand the true meaning of asynchronous transmission, well let’s figure this example to explain, in a very large web part, you can have various modules, which module is our very small module, but comments may involve many may involve paging, if every time we in order to see the comments on the next page, It would be a waste of server resources and bandwidth if you clicked the next page and asked the server to refresh the entire page resources. (If the comment text changed, would you have to render all the other modules?)

So we do what’s called AJAX asynchronous update, which is to ask JavaScript for the next page’s comment data (using JSON as the data interaction text), and JavaScript gets the JSON string that contains the comment information that the page needs. Then our powerful JavaScript will render this part of the reenactment to the corresponding location in the comment module.

In this process, we not only save bandwidth, improve the response speed, but also improve the relative load capacity of the server (less resources per request), improve the user experience, and improve —— (omitted swastik)

Cross-platform webservice:

What I mentioned above is the interaction between the front end and the back end, provided that the back end is the same programming language, platform, and provides services to the front end. However, with the development of the Internet, many times will meet the needs of service separation, cross-platform and other services. One of the biggest barriers across languages is the communication of services. You’re not going to call some Java function on my computer directly from your c++ code, are you? To solve this problem, a restful interface and JSON as a text-transfer format can be used to solve the service communication problem.

For example, A company has too many businesses and allocates services to teams A and B. Many times A may need to make A call to B’s service. If team A is all Java and team B is all PHP, Shouting at each other to be the best in the world. What should I do? So it’s a great way to communicate through JSON. The process is briefly shown in the figure:

Non-relational database storage (Nosql)

With the rise of web2.0 sites, the traditional relational database is a little inadequate to handle the very large sites and high concurrency. And non-relational database because of its own characteristics have been very rapid development, non-relational database in large-scale data also has a very good read and write performance, and there is no relationship between the data, intangible between the architecture level brought scalability.

Many non-relational databases based on document storage take JSON as their storage format, among which the famous ones are MongoDB, CouchDB, RavenDB and so on. The stored content is document-type, which also gives you the opportunity to index certain fields and implement some of the functionality of a relational database.

Some of you may ask: if JSON works, can XML do the same?

The answer is no, because the query and change efficiency of XML field is very low. The main reason is that it is difficult for DB layer to build an efficient index for XML field, and the application layer has to do the parsing conversion from character stream to DOM. NoSQL is stored in JSON, which provides primitive support and is much more efficient than traditional relational databases.

In addition, search engines like Elasticsearch provide all their features and functionality with JSON and Java apis. Json is increasingly used in open source middleware!

(Multiple choice) Exercises: Json is commonly used in which of the following areas? (ABC)

  • Front-end Ajax asynchronous interaction
  • Webservice provides interfaces
  • Non-relational database data storage

Reject sibuxiang, json syntax requirements

Json syntax Rules

Json syntax is a subset of JavaScript syntax, and JSON is generally used to transfer objects and arrays. That is, json syntax is part of JavaScript syntax (JavaScript syntax that satisfies a particular syntax).

  • Data is stored in name and value pairs separated by commas
  • Curly braces represent objects
  • Brackets indicate arrays

Json Name/value

The format of JSON data is “name “:” value”. The JavaScript concept is: name =” value “, but the json format is different from the JavaScript object format:

  • JavaScript object names can be unquoted, single quoted, or double quoted, but JSON string names can only be double-quoted characters.
  • JavaScript objects can have key values that are other types of data than JSON values, such as functions, and json string pairs can only be numbers, strings (with double quotes), logical values, objects (open brackets), arrays (square brackets), and null.

Json object

Json has two representation structures-objects and arrays, which allow you to represent more complex structures. In Java, json arrays and JSON objects are like lists/arrays (Object types) and objects (maps) in Java. And in many cases, the values of the objects may be nested at multiple levels, there are objects in objects, there are arrays in objects, there are objects in arrays… To some extent, the following diagram shows the relationship between json objects and arrays:

A JSON object is easy to understand. It represents an entity that has some other properties, such as a number, a string (with double quotes), a logical value, an object (with open brackets), an array (with brackets), or null. In the Java language it corresponds to an entity class or a Map, some of which describe names and values in terms of keys.

var a = {"name":"bigsai" , "sex":"man"."school": {"name":"Erudite Valley"."localtion":"Bei Jing"}};
Copy the code

The value can be (.). Or ([]) values, for example, a.n ame (a.s ex) and a [] “name” (a [” sex “]), code interpretation is as follows:

Object set objects: can pass (.) Or ([]). The code is interpreted as follows:

Traversal: You can use for-in to traverse objects. The code is interpreted as follows:

Modify the

delete

var a = {"name":"bigsai" , "sex":"man"."school": {"name":"Erudite Valley"."localtion":"Bei Jing"}};
a.name+""+a["name"]
a.school
a["school"].name

for (key in a){// Iterate over the object
    console.log(key+""+a[key]); } a.name="saisai"
a["sex"] ="woman"
a
delete a["school"]
a

Copy the code

Json array

Once you’ve learned about JSON objects, json arrays are a lot easier to learn. A JSON array is different from a JSON object. Json arrays are represented by brackets ([]), values are separated by commas (,), and the array values need to be of a valid JSON data type (string, number, object, array, Boolean, or NULL).

var names=["bigsai"."bigpian"."bigbig"];/ / the json array
var students=[{"name":"bigsai"."high":180}, {"name":"bigpian"."high":165}, {"name":"Yao Ming"."high":226}];// An array of objects
Copy the code

Value: The value can be specified by brackets ([]), for example, names[0] or names[“0”]. The example code is as follows:

Array set object

traverse

Modify the
[]

delete

var names=["bigsai"."bigpian"."bigbig"];/ / the json array
var students=[{"name":"bigsai"."high":180}, {"name":"bigpian"."high":165}, {"name":"Yao Ming"."high":226}];// An array of objects
names["0"] +""+names[0]// Json array value
students[2] ["name"] +Height:+students[2].high// Json array inside object (object inside array)
for (i in names){  console.log(names[i]);  }/ / for the in traverse
for (i=0; i<names.length; i++){console.log(names[i]); } names[0] ="bigsai666";
delete names[0];
names
Copy the code

JavaScript objects VS JSON objects VS JSON strings

JavaScript objects, JSON objects, and JSON strings are often confused and confusing when it comes to JavaScript.

var a1={ name:"bigsai" , sex:"man" };/ / JavaScript object
var a2={'name':'bigsai' , 'sex':'man'};/ / JavaScript object
var a3={"name":"bigsai" , "sex":"man"};// JavaScript objects that satisfy the JSON format
var a4='{"name":"bigsai" , "sex":"man"}';/ / a json string
Copy the code

In general:

  • JavaScript objects: Values in JavaScript are objects except for strings, numbers, true, false, NULL, and undefined.

  • Json object: This is not quite accurate, there is no separate JSON object, we often say that the JSON object is essentially a JavaScript object that meets the requirements of the JSON format. As with the A3 object.

  • Json string, a string that satisfies the syntax format of JSON (JSON is a data format), sometimes called a JSON string.

Just to add a few words here, you might be a little confused about json objects, and you might come across json objects in other places. First of all, JSON is a data format, and JSON has both object and array representation formats.

  • When you say json object, JSON array. It just goes straight to the two representation structures of JSON. It is mainly about structure.
  • In JavaScript, we usually say json object, JSON array usually refers to the JavaScript object that satisfies the JSON format, JavaScript array.
  • In Java we sometimes say JSON object, JSON array, this is actually a third-party toolkit based on the JSON specification wrapped JSONObject, JSONArray class.

In general, we usually talk about JSON objects, JSON arrays, it is essentially a data format. But objects and arrays that meet the format requirements in different languages are called JSON objects and JSON arrays.

Which of the following is a JavaScript object that satisfies the JSON format? (D)

  • A. {name: “”, value:” “};
  • B. {‘name’ : ‘name’, ‘value’ : ‘very well’};
  • C. {name: “1 “, age: “18”};
  • D. {“name” : “age”, “age” : 25};

summary

The syntax rules for JSON are relatively simple. For json syntax format, you should remember that json data names can only be strings with double quotes (“”), and json object values should remember that there are several types that meet the requirements. In the case of JSON objects and JSON arrays, there are two kinds of representation structures for JSON, and the flexibility of JSON also allows the two types to be nested within each other to represent more complex structures.

(Multiple choice) Since you have learned json objects, arrays, and some basic syntax with me, which of the following types can not be a JSON object value? (D)

  • string
  • digital
  • Json object/JSON array
  • function

Google Gson, lean but powerful

Introduction to serialization/deserialization

Previously, we learned some concepts and basic syntax of JSON. We also know that JSON is supported by JavaScript in many languages such as Python, but there are also many languages that do not support JSON (such as our powerful Java). This is a big barrier but it doesn’t stop us from using JSON in the Java language. We can make Java support JSON processing by adding some toolkits.

These toolkits are capable of converting JSON strings into Java objects for use in Java. In turn, Java objects can be converted to JSON strings, which can be used more widely elsewhere. The process of converting a Java object to a Json string is called Serialization, and the process of converting a Json string to a Java object is called Deserialization.

From the Java point of view, Java objects need to be broken up from a whole object into fragments that are sequentially written to a JSON string. This is the process of serialization. Deserialization is the process by which the fragments of a JSON string are in turn reassembled into a complete Java object.

Json itself is not complicated, but in Java, if programmers directly operate json strings, it is a very troublesome and complicated thing, many excellent programmers/teams/companies work hard to study, open source their experience and wisdom for everyone to use, in which, Gson/ Fastjson /Jackson is more popular. Let’s go through them one by one.

Gson introduction

Before studying, do you know what Gson is? Gson is a Google open source Java library that can be used to convert (serialize) Java objects into their JSON representation. It can also be used to convert JSON strings into (deserialize) equivalent Java objects. Gson can work with any Java object, including existing objects without source code. Below is some information on Gson’s Github home page.

  • Provides simple toJson() and fromJson() methods to convert Java objects toJson strings and vice versa
  • Allows conversion of existing non-modifiable objects to JSON
  • Extensive support for Java generics
  • Allows custom representations of objects
  • Support for arbitrarily complex objects (with deep inheritance hierarchies, generics, etc.)

Gson of actual combat

The following and you begin to Gson actual combat, Gson function is more powerful, here and you together to achieve some basic and commonly used use.

First create a Java project (Maven) that will import Gson’s Maven dependencies or JARS. Its Maven dependencies are:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>
Copy the code

With the Gson dependency, it is easy to convert Java objects to Json in two steps:

  • The Gson object can be created directly by new or using GsonBuilder. If the Gson object is created directly by new, the default configuration is used. To use GsonBuilder, you first create the GsonBuilder, then the GsonBuilder calls some configuration methods, and then the create() method is called to build the Gson object.
  • The Gson object is then serialized and deserialized through the toJson(),fromJson() methods.

Convert Javabeans to JSON strings: First create a Student object

public class student {
    private String name;
    private int age;
    private String sex;

    public student(String name, int age, String sex) {// The constructor
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    @Override
    public String toString(a) {// Override the toString method
        return "student{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                ", sex='" + sex + '\' ' +
                '} ';
    }

    public String getName(a) {// Get the name string
        return name;
    }

    public void setName(String name) {// Set object name
        this.name = name;
    }

    public int getAge(a) {// Get age int
        return age;
    }

    public void setAge(int age) {// Set the age value
        this.age = age;
    }

    public String getSex(a) {// Obtain gender
        return sex;
    }

    public void setSex(String sex) {// Set gender
        this.sex = sex; }}Copy the code

Second, convert Javabeans (Students) to JSON strings in the test. Serialization and deserialization are performed primarily through toJson() and fromJson(). ToJson, which literally translates to “reach JSON,” is the conversion of a Java object to a JSON string, i.e., serialization. FromJson, which literally translates to “fromJson,” is what converts json strings into Java objects, also known as deserialization.

//Gson gson= new GsonBuilder().create(); // You can customize some configurations
 Gson gson=new Gson();// Create a JSON object
// Java object to json
 student stu=new student("Ben".22."man");
 String stustr=gson.toJson(stu,student.class);/ / json into a string
 System.out.println(Student object is+stu.toString());
 System.out.println("Convert to json string:"+stustr);
 
 // Json to Java object
 / / / meet the conditions of json string {" name ":" Tony ", "age" : 32, "sex" : "woman"}
 String jsonstr="{\"name\":\"tony\"," +
                 "\"age\":32," +
                 "\"sex\":\"woman\"}";
 student jsonstrobject=gson.fromJson(jsonstr,student.class);// Convert to a student object
 System.out.println("Json string is"+jsonstr);
 System.out.println("Convert to student object as:"+jsonstrobject.toString());
Copy the code

The result of execution is:

Convert Java collections to JSON strings:
Map<String,String>
List<Object>
String[]

 Gson gson=new Gson();// Create a JSON object
//Map
 Map<String,String>map=new HashMap<>();//Map
 map.put("Erudite Valley"."666"); map.put("Little brother"."Come on.");
 //List
 List<Object>list=new ArrayList<>();/ / the List type
 list.add("hello"); list.add("world"); list.add(map);//String[]
 String []str={"Hello"."World"};//String

 String mapTojsonStr=gson.toJson(map);//{" little brother ":" come on "," Erudite Valley ":"666"}
 String listTojsonStr=gson.toJson(list);//["hello","world",{" little brother ":" come on "," Eruderu ":"666"}]
 String strTojsonStr=gson.toJson(str);//["Hello","World"]
 System.out.println("The Map into json."+mapTojsonStr);
 System.out.println("The List into json."+listTojsonStr);
 System.out.println("String [] to json,"+strTojsonStr);
Copy the code

The result of execution is:

fromJson(String json, Class<T> classOfT)
fromJson(String json, Type typeOfT)

 Gson gson=new Gson();// Create a JSON object
 String mapTojsonStr="{\" little brother \":\" come on \",\" erudite valley \":\"666\"}";//{" little brother ":" come on "," Erudite Valley ":"666"}
 String listTojsonStr="[\" hello \ ", \ "world \", {\ "little bro \" : \ "to go \", \ "erudite valley \" : \ "666 \"}]";//["hello","world",{" little brother ":" come on "," Eruderu ":"666"}]
 String strTojsonStr="[\"Hello\",\"World\"]";//["Hello","World"]
 // Method 1 is convenient and concise.
 //Map<String,String>map1=gson.fromJson(mapTojsonStr,Map.class);
 // Method 2 can obtain data types such as generics
 Map<String,String>map1=gson.fromJson(mapTojsonStr,new TypeToken<Map<String,String>>(){}.getType());
 List<Object>list=gson.fromJson(listTojsonStr,List.class);
 Map<String,String>map2=(Map<String,String>)list.get(2);
 String str[]=gson.fromJson(strTojsonStr,String[].class);
 System.out.println("Turn json Map."+map1.toString());
 System.out.println("Turn json List"+list.toString());
 System.out.println("Is map1 and MAP2 equal?"+map2.equals(map2));/ / equal
 System.out.println("String[]:"+ Arrays.toString(str));
Copy the code

The output is:

The above just introduces the conversion of Java objects and JSON strings. In fact, Gson is not only easy to start with, but also has other very powerful functions. In addition to the conversion of Java objects and JSON strings in Gson development, We often operate on JsonObjects directly (just like JavaScript does with JSON strings). Here you need to learn about the JsonEelement, JsonObject, JsonArray, JsonPrimitive,JsonNull, etc.

Different data types have their own usage scenarios. Here are the differences and connections between the data types:

  • JsonElement: A class that represents a Json element. It can be JsonObject, JsonArray, JsonPrimitive, or JsonNull. Do you think you could understand this List in the Java (Arraylist, and LinkedList), Map (HashMap. TreeMap, ConcurrentHashMap) and so on. It can also be understood as the relationship between the class of Object and other classes.
  • JsonObject: A class that represents an object type in Json. Objects consist of name-value pairs, where the name is a string and the value is any other type of JsonElement.
  • JsonArray: A class that represents an array type in Json. An array is a list of JsonElements, each of which can be of a different type. This is an ordered list, meaning that the order in which the elements were added is preserved.
  • JsonPrimitive: Class that represents Json base values. The base value can be a String, a Java base type, or a wrapper class for a Java base type.
  • JsonNull: A class that represents a Json null value.

With these data types, you might be asking: Why do you need these data types when JSON strings can already be interchanged with Java objects? The answer is that these data types give Java one more way to handle jSON-formatted data. On the one hand, making Java more flexible in handling JSON-formatted data, on the other hand, directly manipulating JsonObject, JsonArray, and so on can simplify the workflow in some scenarios.

In fact, these data types are equivalent to using Java data structures to construct a JSON data structure and methods (Java itself does not directly support JSON), allowing us to directly use and manipulate JSON.

A lot of times what we’re doing in the background is we’re taking a JSON string, and it might have a complex internal structure, and if we turn it into a Java object, we might have to write a Java entity, but if we manipulate the JSON object directly, we might save some operations and processes, and if we just add or delete a small part of it, Then this choice is also a good plan. Of course, the specific use method and scheme also need to be judged according to the specific business!

(multiple choice) since the study of Gson, then let’s test whether you really master the key function of Gson, carefully think oh, this problem is a bit ruthless, a mistake all wrong yo :(AD)

  • A. The toJson() function converts an object to A JSON string.
  • B. The toJson() function turns a JSON string into an object.
  • C. The fromJson() function converts an object to a JSON string.
  • D. The fromJson() function turns a JSON string into an object.

Fastjson, alibaba’s “black technology”

Fastjson introduction

In addition to Google Gson, we also have a very powerful Java serialization toolkit – FastJSON. Here is the fastJSON home page on Github:

  • Fastjson is Alibaba’s open source JSON parsing library, which can parse JSON format strings, support serialization of Java beans to JSON strings, and deserialization from JSON strings to Javabeans.

In addition to being open source from Ali, FastJSON also has excellent performance. The advantages of FastJSON are as follows:

  • Fast: FastJSON is fast relative to other JSON libraries. Since the release of version 1.1.x in 2011, fastJSON has never been outperformed by other JSON libraries implemented in Java.
  • Extensive use, complete testing. It has a wide range of applications within Ali.
  • Simple to use and functional. Support for generics, complex types, etc.

Fastjson of actual combat

We need to import dependencies. We need to download jar packages to import dependencies or maven dependencies.

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
Copy the code

Fastjson and Gson are similar but different. Fastjson also has its own implementation of the JSONObject, JSONArray class, which was introduced earlier in Gson. We add JSONObject to the conversion. The following three classes are provided in FastJSON: (1) JSON: FastJSON parser for converting JSON format strings to JSON objects and Javabeans. (2) JSONObject: Json object provided by fastJson. (3) JSONArray: fastJson provides json array objects.

First, we also define a student class (same as Gson’s Student class)

public class student {
    private String name;
    private int age;
    private String sex;

    public student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    / / get set method
}
Copy the code

In the test code, we separately write some code to achieve the conversion of the three, but there are still many methods of JSONObject, JSONArrray, JSON and FastJSON, which can not be shown in detail here:

 // Convert object to JSON string, JSONObject
student student1=new student("xiaoming".5."man");
String jsonstr1= JSON.toJSONString(student1);// Convert the object to a JSON string
JSONObject jsonObject1=(JSONObject) JSON.toJSON(student1);// Object to JSONObject
System.out.println(jsonObject1.toString());
System.out.println(jsonstr1+"\n");
// Convert the json string to a Java object, JSONObject
String jsonstr2="{\"age\":5,\"name\":\"xiaoming\",\"sex\":\"man\"}";
JSONObject jsonObject2=JSON.parseObject(jsonstr2);// Convert the json string to a JSONObject
student student2 = JSON.parseObject(jsonstr2,student.class);// Convert the json string to a Java object
System.out.println(jsonObject2.toString());
System.out.println(student2.toString()+"\n");

//JSONObject to Java object, json string
JSONObject jsonObject3=jsonObject2;
jsonObject3.put("age".18);// Change the age
student student3=jsonObject3.toJavaObject(student.class);//JSONObject to Java object
String jsonstr3=jsonObject3.toJSONString();// Convert JSONObject to JSON string
String name=jsonObject3.getString("name");/ / JSONObject value
int age=jsonObject3.getInteger("age");
String sex=jsonObject3.getString("sex");
System.out.println("Name"+name+" 年龄"+age+"Gender"+sex);
System.out.println(student3.toString());
System.out.println(jsonstr3+"\n");
Copy the code

The corresponding output results are as expected:

Json strings, JsonObjects, and Java collections are converted to each other

// Map related transformation
Map<String,String>map1=new HashMap<>();
map1.put("name"."xiaoming"); map1.put("sex"."woman");
String jsonstr=JSON.toJSONString(map1);//Map to json string
JSONObject jsonObject=(JSONObject) JSON.toJSON(map1);// Convert the Map to a JSON object

System.out.println(jsonstr);
System.out.println(jsonObject.toString());
//Map
      
       map2=JSON.parseObject(jsonstr,Map.class); / / way
      ,string>
Map<String,String>map2=JSON.parseObject(jsonstr,new TypeReference<Map<String, String>>(){});// Mode 2: convert a JSON string to a Map
Map<String,String>map3=jsonObject.toJavaObject( new TypeReference<Map<String, String>>(){});//JSONObject
System.out.println(map2.toString());
System.out.println(map3.toString());
Copy the code

The console output is:

//List related transformation
List<Map<String,String>>list1=new ArrayList<>();/ / collection
Map<String,String>map1=new HashMap<>();
map1.put("name"."map1");
Map<String,String>map2=new HashMap<>();
map1.put("name"."map2"); map2.put("sex"."man"); list1.add(map1); list1.add(map2); String jsonstr=JSON.toJSONString(list1);// Turn the list into a json string
JSONArray jsonArray =(JSONArray) JSON.toJSON(list1);/ / the list jsonArray
JSONObject jsonObject=jsonArray.getJSONObject(0);
System.out.println(jsonstr);
System.out.println(jsonArray+""+jsonArray.get(0));

// Turn the json string to list
List<Map<String,String>>list2=JSON.parseObject(jsonstr,new TypeReference<ArrayList<Map<String,String>>>(){});
//List
      
       list3=JSON.parseArray("",student.class); // The conversion mode of the normal list
      
System.out.println(list2.get(0).equals(map1)+""+list2.get(1).equals(map2));// If it is equal, the serialization proves successful
System.out.println(list2.toString());
Copy the code

The output is:

These two are used a lot in the development process, each has its advantages and disadvantages, and here is only a small part of the content, to further study also need to understand the official comprehensive API (Gson official API, fastJSON official document). But for FastJSON, there may be some bugs and unstable factors, but Ali will soon fix. Consider the security of FastJSON in practice.

Fastjson (D) FastJSON (D) FastJSON (D)

  • A.JSON
  • B.JSONObject
  • C.JSONArray
  • D.JsonElement

With open source recognition, Jackson is the real king

Jackson is introduced

And finally, the more mature Jackson. Jackson is a framework that serializes Java objects to JSON strings and deserializes JSON strings to Java objects. Here’s Jackson’s Github home page:

  • The students started early, had a high international popularity, and the community learning content was rich.
  • Secure and stable, it is a built-in serialization framework for many open source frameworks (such as Springmvc).
  • Parsing large JSON files is efficient, consumes less memory, and performs well.
  • It has a flexible API that can be easily extended and customized.

Jackson of actual combat

Jackson uses only one JAR to use Gson and FastJSON. Jackson does not integrate everything into one JAR, but it is divided into several different modules (different modules with different functions). Let’s introduce Jackson’s dependencies first:

<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.11.0</version>
</dependency>
<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>
<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.11.0</version>
</dependency>
Copy the code

Now that we have Jackson dependencies, we can actually do this. There are three ways to manipulate JSON in Jackson:

  • Streaming API – Uses a Stream approach for fine-grained control over each component of Json, with JsonParser reading the data and JsonGenerator writing the data. Json streaming: The lowest cost, the fastest read/write.
  • Tree model – The JSON file is represented as a tree in memory, and individual JSON nodes are processed through JsonNode, similar to the DOM parser for XML. ObjectMapper is the most flexible way to build a JsonNode tree.
  • Databind module -ObjectMapper reads/writes JSON, which is the most convenient way to serialize and deserialize JSON. (The method used in this case)

For Javabeans, we create the Student class (note that the Jackson class must have an empty parameter constructor) :

public class student {
    private String name;
    private int age;
    private String sex;

    public student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    public student(a){}// Empty parameter constructor
    // Get set method toString method
}
Copy the code

In the test code, you first create an ObjectMapper object, which is needed for both serialization and deserialization. The Java object can then be turned into a JSON string (serialized) by using the writeValueAsString() function. Json strings can be converted to Java objects (deserialization) by readValue(). The code is shown below:

// Create an ObjectMapper object
ObjectMapper mapper=new ObjectMapper();
// Serialized entity class
student stubigsai=new student("bigsai".6."man");
// Serialize the writeValueAsString() method
String stubigsaistr=mapper.writeValueAsString(stubigsai);
System.out.println(stubigsaistr+"\n");

// Deserialized json string
String stuxiaohongstr="{\"name\":\"xiaohong\",\"age\":8,\"sex\":\"woman\"}";
// The readValue() method deserializes
student stuxiaohong= mapper.readValue(stuxiaohongstr,student.class);
System.out.println(stuxiaohong.toString());
Copy the code

For the above code execution result is:

Convert Java collections to JSON strings

// Create ObjectMapper entity class
ObjectMapper mapper=new ObjectMapper();
// Need serialized Map and List
Map<String,Object>map1=new HashMap<>();
map1.put("Erudite Valley"."666"); map1.put("bigsai".Awesome!);// Note that the two 666s are of different types
map1.put("string".new String[]{"bigsai"."Erudite Valley"});
// Serialize the result
String map1str=mapper.writeValueAsString(map1);
System.out.println(map1str+"\n");

// Mode 1 deserializes the result
Map<String,Object>m1=mapper.readValue(map1str,Map.class);
// Mode 2 TypeReference specifies the deserialization type (suitable for generic and complex types)
Map<String,Object>m2=mapper.readValue(map1str, new TypeReference<Map<String, Object>>() {});
System.out.println(m1.toString());
System.out.println(m2.toString());
Copy the code

The execution result is:

Official Jackson Documents

Gson VS fastjson VS jackson

All three Java serialization/deserialization JSON frameworks have been introduced. All three are excellent frames, no doubt, but in contrast, it hurts a bit.

The name of the Gson fastjson Jackson
Community ecology good general good
Ease of use Easy to use Easy to use general
Small file speed The fastest faster The slower
Large file speed The slower faster faster
The stability of stable general stable
Installation Package Size A very small smaller general

To sum up: Gson: lightweight and concise, suitable for parsing small and medium-sized JSON files. In large JSON files, the efficiency is slightly poor, and its functions are more comprehensive, good ecology. Jackson: Processing large files is faster and more stable than FastJSON. The ecology is better. Fastjson: Fast, but often with security problems. General ecology, mainly for domestic use.

The choice of JSON framework is based on your own needs. For testing or simple personal use, Gson and FastJSON are recommended to get started. If you need to go online, then fastJSON should be used with caution. Some data may fail serialization.

In the end of the introduction, secretly praise our FastJSON main contributor Wen Shao, not only is the FastJSON open source Wen Shao is also another open source framework major contributor – DruID (Ali database connection pool), so the author is very hard to dedicate himself to the cause of open source, service more people, praise!! I hope that in the future, we can do something like Wen Shao! Come on!

Json is easy to use, but json can also be very complex, depending on your specific business use and requirements. Hopefully, in the future, you will be able to use json in the following ways: To json understanding and application can have a deeper step of cognition! Come on, see you next time!

(Single choice) Since the comparison of Gson, FastJSON,Jackson, so little old brothers and sisters, I come to test your understanding of the three how, so the question comes, you show me the following is wrong? (B)

  • A. Son is small in size, but rich and powerful in functions, and the community ecology is complete. Processing small files is more efficient.
  • B. AstJSON is fast, popular both at home and abroad, and the community ecology is good.
  • C. Johnson is widely used in open source frameworks, which is stable and efficient, and has the highest popularity and recognition.
  • Son is open source by Google, FastJSON is open source by Ali, and Jackson is open source by the fastXML team.

A profound

With all that said, it’s important for us to understand how to operate JSON in Java, so let’s start with a small case of transformation. Gson, fastJSON, Gson, fastJSON, Gson, fastJSON

JavaBean to JSON string

Let’s say we have a teacher class that has two attributes, name and age.

public class teacher {
    private String name;
    private int age;
    // Omit the get set and constructor
}
Copy the code

First we have an object

teacher teachersai=new teacher("bigsai".22);
Copy the code

Can you think about what the json string of this object would look like?

Yes, the answer is this:

{"name":"bigsai","age":22}

In the case of Gson, this is how we operate:

Gson gson=new Gson();
String teacherstr=gson.toJson(teachersai);
System.out.println(teacherstr);//{"name":"bigsai","age":22}
Copy the code

What does fastJSON look like?

String teacherstr=JSON.toJSONString(teachersai);
System.out.println(teacherstr);//{"name":"bigsai","age":22}
Copy the code

This is how you turn your Java object into a JSON string, which is pretty simple, because fastJSON makes a lot of the methods in JSON static, so we don’t even need to create this object.

Convert json strings to Javabeans

If we have a string that needs to be turned into a Java Teacher object, what do we need to do?

String teacherpian="{\"name\":\"bigpian\",\"age\":21}";//{"name":"bigpian","age":21}
Copy the code

The Gson object is created in one line of code:

Gson gson=new Gson();
teacher teacherp=gson.fromJson(teacherpian,teacher.class);
Copy the code

In the same way, let’s do fastJSON in one line:

teacher teacherp=JSON.parseObject(teacherpian,teacher.class);
Copy the code

Is it easy? Of course, if you are careful and studious, you will certainly find that there are other ways to write it, practice depends on individual, and more usage is sure to need to dig!

This paper summarizes

This is the end of a fun and enjoyable introduction to JSON. You’ve learned about JSON, the similarities and differences between JSON and XML, and the applications of JSON in the Web and non-relational databases. Through a series of introduction, comparison, combined with the actual scene believe that you know JSON must be very clear.

Then the article introduces the syntax rules of JSON and the actual operation of json in Java, learn and compare Gson, FastJSON, Jackson applications and the difference between them, I believe you also master the actual ability of JSON in Java language. And can flexibly use which kind of framework according to their own needs, and in-depth research.

Json is the product of web technology progress and development, it is a data exchange format. It is almost an inevitable technical point for programmers at the front and back ends. I hope you can review the course more and more in the future, combined with other textbook texts, etc., to ** transform JSON from site to Buddha! ** Come on, see you next time!

bigsai