In depth analysis of three ways to build JSON strings (recommended)

JSON is a lightweight data exchange format, which is very common. Especially when AJAX is used, it is more common to encapsulate data into JSON string in the background. When I was working on a project, I used several methods to convert an array or list set into a JSON string at the back end. Now I think back, I even forgot. Now let's summarize and thoroughly recall these ways of building JSON strings.

A large number of code examples are provided in the notes. It should be noted that most of the code examples are typed and tested by myself. Please correct the deficiencies~

1、 Fastjson of Alibaba

1. Fastjson is a JSON processor written in Java language. It is developed by Alibaba company and has powerful functions.

To use third-party tools, of course, you need to import the jar package, just import fastjson-1.2 8. Jar. You can download the jar package directly on the Internet or contact me.

Let's start with a simple instance of fastjson. The following code constructs an instance of customer, converts this instance into a JSON string, and calls com alibaba. fastjson. The tojsonstring () method of JSON passes in the customer instance

Print results: {address ":" Beijing "," custname ":" Tom "," Id ": 1}

Another small test is to convert the customer collection of a list into a JSON string. In line 22, you can directly call the tojsonstring () method of JSON and pass in the list collection

Print results: [{address ":" Beijing "," Id ": 1}, {address": "Shanghai", "custname": "Bob", "ID: 1}]

2. Let's take a closer look at the following situation: a customer set of list is created in line 3, and a repeated add operation is performed in lines 10 and 11. What is the print result?

Print results: [{"address": "Beijing", {"$ref": "$[0]}], you can see that the second customer instance is not printed, which proves that fastjson prohibits circular reference by default. If you want to change this situation, you need to pass the second parameter serializerfeature in the tojsonstring() method of JSON Disablecircularreferencedetect can be solved as follows:

The print result is: [{"address": "Beijing", {"address": "Beijing", "Id": 1}]. It is recommended to add the second parameter when using the tojsonstring() method of JSON in the future

3. Take a closer look at a common problem. Department and manager classes maintain a two-way one-to-one association. There are references to manager class in department class and department class in manager class. Look at the following code: the association relationship is set in lines 11 and 12, and the JSON string is converted in lines 14 and 15. What will be the result?

The answer is that an exception is thrown, common Java Lang. stackoverflowerror, the reason for throwing exceptions is that both parties maintain the association relationship and enter an endless cycle. How to solve this problem? You can add @ jsonfield (serialize = false) annotation on one side, as shown in line 7

The printing results are: {dept ": {deptid": 2, "deptname": "dev"}, "MGrid": 1, "mgrname": "Tom"}, and the results are also very satisfactory.

4. Finally, a fastjson tool class is provided, which can be used directly during development for your reference

2、 Jackson

1. You also need to import jar packages. There are three jar packages imported by Jackson

The specific use is also illustrated by a small example:

A customer class is defined. Lines 38 and 43 define two additional get methods and assign values directly. Create the objectmapper object in the main method, call its writevalueasstring() method, pass in a single object or a collection of objects, and the corresponding JSON string will be returned, The print result is: [{"Id": 1, "name": "Tom", "city": "Beijing"}, {"Id": 2, "name": "Bob", "city": "Beijing"}]. You may find that the school in the getschool() method defined in line 43 is not printed because we added the @ jsonignore annotation on this method. When constructing JSON string, we will ignore this attribute. Think about it, This annotation is added to the get method, which also shows that Jackson constructs JSON strings based on the getter method.

2. As before, we want to see if Jackson prohibits circular references. Similar codes:

Take a look at the output results: [{"Id": 1, "address": "Beijing"}, {"Id": 1, "address": "Beijing"}], and the results are obvious.

3. Let's take another look at the example of two-way one-to-one mapping between department and manager tested in fastjson. How will Jackson perform

The same exception is caused by: Java Lang. stackoverflowerror, our idea is the same as testing fastjson. We add @ jsonignore annotation to the manager reference in the Department. The exception is solved, but the print result is very satisfactory. The result is: {deptid ": 2," deptname ":" dev "}, which is far less than the output result of fastjson. This shows the power of fastjson.

3、 Google gson

1. Let's see how to use: jar package only needs a gson-2.2 4. Jar, there is nothing to say about converting ordinary objects and collections into JSON. Let's simply demonstrate how to convert the list collection into JSON strings, directly new the gson object, call its tojson () method, and pass in the object to be converted.

Print result: [{"address": "Beijing", "Id": 1}]

2. Is circular reference prohibited?

The output result: [{"Id": 1, "address": "Beijing"}], obviously not.

3. If there is a two-way one-to-one association mapping, Google gson will also have an endless loop problem, resulting in Java Lang. stackoverflowerror exception, but gson does not provide us with an annotation. To solve this problem, LZ provides a solution idea. Google gson uses the exclusionstrategy strategy to serialize a field or a domain. You can define an annotation through this interface to solve this problem. However, it is recommended that you use fastjson to convert objects involving two-way Association into JSON.

4、 Simple comparison of three methods

LZ compares three ways to construct JSON strings from the following aspects:

1. Jar packages: fastjson and Google gson are obviously the winners. Jackson needs to add three jar packages.

2. Convert simple objects or collections into JSON: if ordinary simple objects or collections are converted, Jackson and Google gson may win. At least the construction is convenient.

3. Involving the transformation of two-way relationship: there is no doubt that Alibaba's fastjson will win.

It is suggested that we reasonably choose a certain method according to our own needs in the actual development.

The above in-depth analysis of the three ways to build JSON strings (recommended) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>