Generation and parsing of JSON in Java

Generation and parsing of JSON in Java

1, What is JSON

JSON: JavaScript Object Notation JS object notation is a language similar to XML. Compared with XML, it is smaller, faster and easier to parse. It is mainly used for network data transmission of project front end and Server.

2, JSON syntax

object

An object is represented by a brace {}, and the attributes of the object are described by key value pairs in {}

be careful:

Keys and values are connected by colons, and multiple key value pairs are separated by commas.

The key of key value pair should be enclosed with quotation marks (generally, when Java parsing, the key will report an error without quotation marks, but JS can parse correctly); The value of key value pair can be any data type in JS

Format:

{

Key 1: value 1,

Key 2: value 2,

.
.

}

Case: use JSON to describe a book. Attributes: book title and introduction

{

"name":"Self-control",

"info":"How to improve your self-control"

}

Array format

[] represents an array. In JSON, arrays and objects can be nested with each other

Format:

[element 1, element 2,...]

Case:

{

"name": ["self control", "top of the wave"]

}

3, Conversion between JSON and Java objects

At present, the conversion between JSON and Java objects is mainly operated by referencing Gson class library or fastjason class library

Gson

Gson is a Java class library provided by Google to map between Java objects and JSON data. You can convert a Java object to a JSON string, or you can convert a JSON string to a Java object.

Convert Java objects to JSON strings

Steps:

1. Introduce JAR package

2. Write the following code at the position of the JSON string to be converted:

String json = new Gson(). Tojson (object to be converted);

Case:

Write a Book object class

public class Book {

    private String id;
    private String name;
    private String info;
    
    @Override
    public String toString() {
        return "Book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }
    
    public Book(String id, String name, String info) {
        this.id = id;
        this.name = name;
        this.info = info;
    }
    
    public Book() {
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return Objects.equals(id, book.id) &&
                Objects.equals(name, book.name) &&
                Objects.equals(info, book.info);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id, name, info);
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getInfo() {
        return info;
    }
    
    public void setInfo(String info) {
        this.info = info;
    }

}

Convert Book object to JSON

public class toJSON {

    public static void main(String[] args) {
        //1. Create a Gson object
        Gson g = new Gson();
        //2. Conversion
        Book b = new Book("10","Self-control","How to improve self-control");
        String s = g.toJson(b);
        System.out.println(s);
    }

}
The output is:
{"id":"10","name":"Self-control","info":"How to improve self-control"}

Converts a JSON string to a Java object

1. Introduce JAR package

2. Write the following code at the location of the Java object to be converted:

Object = new gson() Fromjason (JSON string, object type. class);

be careful:

When the converted Java object does not contain the attributes in the JSON string, the attributes may be lost during the conversion process. Solution: convert to Map collection

Case:

Convert JSON string to Book object

public class toBook {

    public static void main(String[] args) {
        //1. Create a Gson object
        Gson g = new Gson();
        //2. Conversion: {"id":"10","name": "self-control", "info": "how to improve self-control"}
        Book b = g.fromJson("{\"id\":\"10\",\"name\":\"Self-control\",\"info\":\"How to improve self-control\"}", Book.class);
        System.out.println(b.getId());
    }
}
result:
10

Convert JSON string to Map collection

be careful:

When there are key value pairs in array format in JSON, the key value pairs in array format are converted to List type

public class toMap{

    public static void main(String[] args) {
        //1. Create a Gson object
        Gson g = new Gson();
        //2. Conversion  
        HashMap data = g.fromJson("{\"id\":\"10\",\"name\":\"Self-control\",\"info\":\"How to improve self-control\", \"page\":[\"Time control mode\",\"Self suggestion\"]}"HashMap.class);
        List page=(List) data.get("page");
        System.out.println(data.get("id"));
        System.out.println(page.get("1"));
    }

}
Operation results:
10
 Time control mode

FastJson

Fastjason is a Java class library provided by Alibaba for mapping between Java objects and JSON data.

Convert Java objects to JSON strings

Steps:

1. Introduce JAR package

2. Write the following code at the position of the JSON string to be converted:

Compared with gson, fastjason does not need to create new objects

String json = JSON. Tojsonstring (object to be converted);

Converts a JSON string to a Java object

Steps:

1. Introduce JAR package

2. Write the following code at the position of the JSON string to be converted:

Transfer object

String json = JSON.parseObject(JSON string, type. class);

Transfer List

List < type > List = JSON Parsearray (JSON string, type. class);

4, Summary:

JSON for mobile devices, especially in the case of poor network environment and traffic restrictions, data transmission in XML format will save traffic and have higher transmission efficiency.

reference resources

Three parsing methods of json_ In a hurry that year's column - CSDN blog_ json parsing

JSON data parsing just look at this - Jianshu (jianshu.com)

Keywords: Java JSON

Added by yuan on Sun, 30 Jan 2022 19:57:44 +0200