Brief introduction and use of JSON

Posted by beebum on Wed, 26 Jan 2022 00:56:42 +0100

Json

1, What is Jason

  • JSON (JavaScript object notation) is a lightweight data exchange format, which is widely used at present.
  • Data is stored and represented in a text format completely independent of the programming language.
  • The concise and clear hierarchy makes JSON an ideal data exchange language.
  • It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

In the JavaScript language, everything is an object. Therefore, any type supported by JavaScript can be represented by JSON, such as string, number, object, array, etc. Look at his requirements and grammatical format:

  • Objects are represented as key value pairs, and data is separated by commas
  • Curly braces save objects
  • Square brackets hold the array

JSON key value pair is a way to save JavaScript objects, which is also similar to the writing method of JavaScript objects. The key name in the key / value pair combination is written in front and wrapped in double quotation marks "", separated by colon: and then followed by the value:

json data instance:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "male"}

The objects of Json and JS are very similar, which is easy to be confused. In fact, Json can be understood as the string representation of JS objects. It uses text to represent the information of a JS object, which is essentially a string.

contrast:

//This is an object. Note that the key name can also be wrapped in quotation marks
var obj = {a: 'Hello', b: 'World'}; 
//This is a JSON string, which is essentially a string
var json = "{"a": "Hello", "b": "World"}"; 

In the front-end, JS also encapsulates methods, so that JSON and JS objects can be converted to each other. If you are interested, you can search by yourself. The following mainly talks about Java's operation on JSON.

2, How Java transforms objects and Json

1,JackSon

1.1 preparation for use

SSM project:

Dependency needs to be introduced manually:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

SpringBoot project:

SpringBoot comes with JackSon, which eliminates the need to manually introduce dependencies

1.2. Simple use

pojo entity class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    public Integer id;
    public Integer age;
    public String name;
}

controller:

    @RequestMapping(path = "/json")
    public String json() throws JsonProcessingException {
        //Create an object mapper of jackson to parse the data
        ObjectMapper mapper = new ObjectMapper();
        //Create an object
        User user = new User(1, 3, "Xia fan");
        //Parse our object into json format
        String json = mapper.writeValueAsString(user);

        return json;
    }

Operation results:

1.3. Processing date type

Enter the ObjectMapper object mapping class and find that it returns a sequence for date processing:

    public DateFormat getDateFormat() {
        return this._serializationConfig.getDateFormat();
    }

At the same time, it also provides a set method to modify the date format:

    public ObjectMapper setDateFormat(DateFormat dateFormat) {
        this._deserializationConfig = (DeserializationConfig)this._deserializationConfig.with(dateFormat);
        this._serializationConfig = this._serializationConfig.with(dateFormat);
        return this;
    }

Therefore, for operations with dates, we can customize:

DateFormat is an abstract class. We generally use its subclass SimpleDateFormat to operate. The string operation rules of this subclass are as follows:

Examples are as follows:

pojo entity class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    public Integer id;
    public Integer age;
    public String name;
    public Date date;
}

controller:

    @RequestMapping(path = "/json")
    public String json() throws JsonProcessingException {
        //Create an object mapper of jackson to parse the data
        ObjectMapper mapper = new ObjectMapper();
        //Create an object
        User user = new User(1, 3, "Xia fan",new Date());
        //Customizing date formats for ObjectMapper objects
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year mm month dd day");
        mapper.setDateFormat(simpleDateFormat);
        //Parse our object into json format
        String json = mapper.writeValueAsString(user);

        return json;
    }

Operation results:

2,FastJson

fastjson.jar is a package specially developed by Ali for Java development. It can easily realize the conversion between json object and JavaBean object, between JavaBean object and json string, and between json object and json string. There are many conversion methods to realize json, and the final implementation results are the same. The biggest advantage is high performance.

2.1 preparation for use

Both SSM and SpringBoot need to introduce dependencies:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.60</version>
</dependency>

2.2. Three main operation categories

JSONObject represents a json object

  • JSONObject implements the Map interface. I guess the underlying operation of JSONObject is implemented by Map.
  • JSONObject corresponds to the json object. You can obtain the data in the json object through various forms of get() methods. You can also use methods such as size(), isEmpty() to obtain the number of "key: value" pairs and judge whether they are empty. Its essence is accomplished by implementing the Map interface and calling the methods in the interface.

JSONArray represents an array of json objects

  • Internally, there are methods in the List interface to complete the operation.

JSON represents the conversion of JSONObject and JSONArray

  • Analysis and use of JSON class source code
  • Carefully observe these methods, mainly to realize the mutual transformation between json objects, json object arrays, javabean objects and json strings.

2.3. Simple use

pojo entity class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    public Integer id;
    public Integer age;
    public String name;
}

controller:

    @RequestMapping(path = "/fjson")
    public String testFjson() throws JsonProcessingException, JSONException {

        User user1 = new User(1, 1, "Xia fan 1");
        User user2 = new User(2, 2, "Xia fan 2");
        User user3 = new User(3, 3, "Xia fan 3");
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);

        String l1 = JSON.toJSONString(list);
        String u1 = JSON.toJSONString(user1);
        String u2 = JSON.toJSONString(user2);
        String u3 = JSON.toJSONString(user3);

        return l1;
    }

Operation results:

Topics: Java JSON jackson fastjson