My learning path - initial experience of JSON

Posted by ppera on Tue, 08 Mar 2022 02:10:54 +0100

JSON learning

Recently, I learned a new content: JSON. After learning, I have a little concept. Write this blog to help me deepen my understanding. It's purely your own personal understanding. If there is any mistake, I hope you can point it out in time and forgive me.


First of all, we need to know something, what it is and what it is used for.

What is JSON

The following is the official introduction of JSON:
come from JSON Chinese website:

JSON(JavaScript Object Notation) is a lightweight data exchange format. It makes it easy for people to read and write. At the same time, it is also convenient for the machine to analyze and generate.
It is a subset of JavaScript programming language, standard ecma-262 3rd Edition - December 1999.
JSON adopts a text format completely independent of the program language, but it also uses the habit of C-like language (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

JSON is based on two structures:

A collection of name/value pairs. In different programming languages, it is understood as object, record, struct ure, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, it is implemented as array, vector, list and sequence.

Generally speaking, it is an expression of data. We use such a format to express our data.

What is JSON used for?

Usually, JSON is used for data exchange between server and client.

JSON syntax

  • JSON data is described by key / value and separated by commas.
  • A brace represents a complete object with multiple key value pairs.
  • Brackets are used to save the array. Multiple objects in the array are separated by commas.
var json = {
               "class1":[
                    {"name":"Zhang San","id":"2021111"},
                    {"name":"Li Si","id":"2021222"},
                    {"name":"Wang Wu","id":"2021333"}
                ]
            }

class1 is a key, and its value is the array saved in brackets.
There are three objects in the array, which are also in the form of key value pairs.
In order to standardize and avoid errors, both keys and values should be in double quotation marks.
Don't add comments in JSON files, which will report errors.
Here is the JSON Chinese website Online editing tools , you can try it yourself.

Try it

1. We create a new web project.

I use Intellij IDEA. Personally, I feel that it is easier to use than eclipse and has a better user experience.
I won't post the specific operation.

2. Create a JSON file with the suffix if json.

Here, a complete object is in braces, and the data saved between objects can be different. We give Zhang San a monitor position.

3. After creating it, we will use it.

The original name of JSON is JavaScript Object Notation. Let's use javaScript to operate it. Create an html file and write javaScript code.

<!DOCTYPE html>
<html>
<head>
    <title>JSON</title>
    <meta charset="utf-8">
<!--    introduce jquery File to process json-->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
        $.ajax({
            type:"get",
            url: "class.json",
            dataType:"json",
            success:function(data) {
                //Convert json objects to strings
                $("#json").html(JSON.stringify(data));
                //Traverse data and output json
                $.each(data,function(index,obj){
                    let job =function (){
                        if(obj["job"]!=null){
                            return "<p>Title:" + obj["job"] + "</p>";
                        }else
                            return "";
                    };
                    $("#json1").append(
                        "<p>full name:" + obj["name"] + "</p>" +
                        "<p>id:" + obj["id"] +"</p>" +
                        job()
                    );
                })
            },
            error:function() {
                alert("request was aborted");
            }
        });
    </script>
</head>

<body>
    <h1>JSONTest</h1>
    <p id="json"></p>
    <div id="json1"></div>
</body>
</html>

result:
We used json Stringify() converts a json object into a string, and the corresponding json Parse converts strings into json objects.
Note: when defining a string, use \ to escape, otherwise it will conflict, such as:

var class="{\"name\":\"Zhang San\"}";

json itself is an object. In addition to directly defining the initialization method at the top, we can also initialize it in the form of an object, such as:

var class1={};
class1.name="Zhang San";
class1.id="2021111";
//array
var teacher={};
teacher.name="Miss Li";
teacher.id="2021777";
var school={};
school.name="Science and Engineering";
school.id="555";
var dep=[teacher,school];

JSON interaction

We said above that JSON is a format for data storage and transmission, which is commonly used for data interaction between server and client. Let's talk about JSON and JAVA.
We said that JSON was designed and used for javascript at first. Later, we found that it was easy to use. Gradually, other languages began to use JSON. Therefore, java engineers developed the JSON toolkit of java, which is used to convert JSON and java objects.

Fastjson

Fastjson is a commonly used json tool, and other tools include Gjson.

fastjson is Alibaba's open source JSON parsing library. It can parse strings in JSON format, support serialization of Java beans into JSON strings, and deserialization from JSON strings to JavaBean s.

It can be used by introducing jar package or injecting dependency:
jar package: https://github.com/alibaba/fastjson/releases
Maven:

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

Fastjson attempt

1. Create a new entity class on the project.

public class student {
    private int id;
    @JSONField(name="full name")
    private String sname;
    @JSONField(name="post")
    private String job;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}

There is an annotation * * @ JSONField(name = "name") * * in the above entity class. I won't say what the annotation is. The annotation can greatly facilitate our operation on json objects. In addition to the above, there are other annotations, which you can understand by yourself.
@JSONField(name = "xx") this annotation can modify the name of the corresponding key of json. For example, if the above example is not annotated, the result is

{"id": 2021111, "job": "monitor", "sname": "Zhang San"}

After annotation:

{"id": 2021111, "name": "Zhang San", "position": "monitor"}

sname was changed to name and job was changed to position
Here, the positions of the name and job keys are changed because fastjson will sort by attribute name from a to z by default when encapsulating json.

2. Then create the test class

import com.alibaba.fastjson.JSON;

public class test1 {
    public static void main(String[] args) {
//        Initialization, because the constructor was not created before, it was added one by one
        student s = new student();
        s.setId(2021111);
        s.setSname("Zhang San");
        s.setJob("monitor");

//      Fast JSON provides JSON objects to complete the conversion between objects and strings
//        java object to json
        String json = JSON.toJSONString(s);
        System.out.println(json);
//        json to java object
        student stu = JSON.parseObject(json,student.class);
        System.out.println(stu.getSname());
    }
}

result:

Fastjson array object

What we converted above is a single object. Let's look at the array.

1. Create a new test class

public class test2 {
    public static void main(String[] args) {
//        If there are 50 people in a class, the position will not be set up
        List class1 = new ArrayList();
        for(int i = 1;i<=50;i++){
            student stu = new student();
            stu.setId(2021 + i);
            stu.setSname("student" + i);
            class1.add(stu);
        }
//        Conversion, or this method
        String json = JSON.toJSONString(class1);
        System.out.println(json);
        //        json to collection
        List<student> students = JSON.parseArray(json, student.class);
        for(student s : students){
            System.out.print(s.getSname() + " ");
        }
    }
}

The result is too long to post.

json toolkit can convert objects and collections of objects into string form, which is commonly used in Ajax.

Encourage each other and hope everyone's efforts will be rewarded.

Topics: Java JSON