This question is something we do almost every day as programmers. How many ways can it be done? Let’s talk about it here.

Four ways to parse

  • The official resolution

  • Google Gson parsing

  • Alibaba FastJson analysis

  • Jackson parsing

A case in field

We will only discuss how objects and JSON can be converted to each other.

Here we create the Maven project so that we can introduce dependencies and actually test our different parsing methods with unit tests.

Now let’s all use the User object and first create the classes we need.

User.java

package org.example;​public class User {​    private String name;    private String sex;    private Integer age;​    public User() {    }​    public User(String name, String sex, Integer age) {        this.name = name;        this.sex = sex;        this.age = age;    }​    public String getName() {        return name;    }​    public void setName(String name) {        this.name = name;    }​    public String getSex() {        return sex;    }​    public void setSex(String sex) {        this.sex = sex;    }​    public Integer getAge() {        return age;    }​    public void setAge(Integer age) {        this.age = age;    }​    @Override    public String toString() {        return "User{" +                "name='" + name + '\'' +                ", sex='" + sex + '\'' +                ", age=" + age +                '}';    }    }​
Copy the code

The official resolution

The official JSON parsing method is cumbersome, so few people use it.

The first step is to introduce dependencies:
<! Json </groupId> <artifactId>json</artifactId> <version>20160810</version></dependency>Copy the code
Step 2, write the test code:
package org.example; import org.json.JSONObject; import org.springframework.stereotype.Component; @componentPublic class JsonTest1 {@componentPublic class JsonTest1 {@param user @return */ public String userToJson(user) user){ JSONObject jsonObject = new JSONObject(user); String jsonStr = jsonObject.toString(); return jsonStr; } /** * json to object * @param json * @return */ public userFromJson(String json){JSONObject JSONObject = new JSONObject(json); String name = jsonObject.getString("name"); String sex = jsonObject.getString("sex"); int age = jsonObject.getInt("age"); User user = new User(name,sex,age); return user; }}Copy the code
Step 3, unit test:
package org.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:spring.xml")public class JsonTest1Test { @Autowired private JsonTest1 jsonTest1; @test public void userToJson() {User User = new User(" User ", "man", 18); String json = jsonTest1.userToJson(user); System.out.println(json); } @ Test public void userFromJson () {String json = "{\" sex \ ": \" man \ ", \ "name \" : \ "qin Ming \", \ "age \" : 18} "; User user = jsonTest1.userFromJson(json); System.out.println(user); }}Copy the code

Google Gson parsing

The first step is to introduce dependencies:
<! --gson--><dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> The < version > 2.8.5 < / version > < / dependency >Copy the code
Step 2, write the test code:
package org.example; import com.google.gson.Gson; import org.springframework.stereotype.Component; @componentPublic class JsonTest2 {@componentPublic class JsonTest2 {@param user @return */ public String userToJson(user)  user){ Gson gson = new Gson(); String json = gson.toJson(user); return json; } @param json * @return */ public User userFromJson(String json){Gson Gson = new Gson(); User user = gson.fromJson(json, User.class); return user; }}Copy the code
Step 3, unit test: same as above (step 3 below is the same as above, so omit below)

Alibaba FastJson analysis

This parsing method is developed by Alibaba, the most efficient, loved by everyone, powerful, want to learn more in-depth can check the FastJson official website API.

The first step is to introduce dependencies:
<! --fastjson--><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> The < version > 1.2.47 < / version > < / dependency >Copy the code
Step 2, write the test code:
package org.example; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Component; / / @componentPublic class JsonTest3 {/** * object to json * @param user * @return */ public String userToJson(User user){ String json = JSONObject.toJSONString(user); return json; } /** * json to object * @param json * @return */ public userFromJson(String json){User User = JSONObject.parseObject(json,User.class); return user; }}Copy the code

Jackson parsing

This parsing method is currently used in some of the most popular frameworks such as SSM and SpringBoot, where the internal JSON parsing is using Jackson, but we often use FastJson as a separate method because it is faster.

The first step is to introduce dependencies:
<! --jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> The < version > 2.9.8 < / version > < / dependency >Copy the code
Step 2, write the test code:
package org.example; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Component; import java.io.IOException; /** * Jackson parse */ @component public class JsonTest4 {/** ** object to json * @param user * @return */ public String userToJson(User user) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(user); return json; } /** * json to object * @param json * @return */ public User userFromJson(String json) throws IOException {ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(json, User.class); return user; }}Copy the code

Extension to the birth of JSON

JSON was born because the details of XML integration into HTML vary from browser to browser, so Douglas Crockford and Chip Morningstar worked together to extract a subset of THE JS data types, As a new data interchange format, there were no compatibility issues when parsing the new data format because the mainstream browsers used common JavaScript engine components, so they named the data format “JavaScript Object Notation”, or JSON, JSON was born!