Detailed explanation of JSON data generation and analysis in Java

  • 2021-09-20 20:20:20
  • OfStack

1. What is JSON

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

2. Syntax of JSON

Object

1 object, denoted by 1 curly brace {}, in which the attributes of the object are described by 1 key-value pair

Note:

Colons are used to connect keys and values, and commas are used to separate multiple key-value pairs.

The key of the key-value pair should be enclosed by quotation marks (usually when Java is parsed, the key will report an error without quotation marks, while JS can be parsed correctly); The value of the key-value pair, which can be any data type in JS

Format:

{

Key 1: Value 1,

Key 2: Value 2,

.
.

}

Case: Describe a book using JSON, Attributes: Title, Introduction


{

"name":" Self-control " , 

"info":" How to Improve Self-control "

}

Array format

[] denotes arrays, which can be nested with objects in JSON

Format:

[Element 1, Element 2,...]

Case:

{

"name": ["Self-control", "Top of the Tide"]

}

3. Interconversion between JSON and Java objects

Transformations between JSON and Java objects are currently performed by referring to either the Gson class library or the FastJson class library

Gson

Gson is the Java class library provided by Google for mapping between Java objects and JSON data. You can convert an Java object to an JSON string or an JSON string to an Java object.

To convert an Java object to an JSON string step:

1. Introducing the JAR package

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

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

Case:

Write an 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 an Book object to an JSON


public class toJSON {

    public static void main(String[] args) {
        //1.  Create 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 junction is: 
{"id":"10","name":" Self-control ","info":" How to improve self-control "}

Convert an JSON string to an Java object

1. Introducing the JAR package

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

Object = new Gson (). fromJson (JSON string, object type. class);

Note:

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

Case:

Convert an JSON string to an Book object


public class toBook {

    public static void main(String[] args) {
        //1.     Create 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());
    }
}
 Results: 
10

Convert an JSON string to an Map collection

Note:

When an array-formatted key-value pair exists in JSON, the array-formatted key-value pair is converted to the final result of List type


public class toMap{

    public static void main(String[] args) {
        //1.     Create 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 method \"]}"HashMap.class);
        List page=(List) data.get("page");
        System.out.println(data.get("id"));
        System.out.println(page.get("1"));
    }

}
 Run results: 
10
 Time control mode 

FastJson

FastJson is an Java class library provided by Ali for mapping between Java objects and JSON data.

Convert an Java object to an JSON string

Steps:

1. Introducing the JAR package

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

Compared to Gson, FastJson does not need to create new objects

String json = JSON. toJSONString (objects to be converted);

Convert an JSON string to an Java object

Steps:

1. Introducing the JAR package

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

Turn object

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

Transform List

List < Type > list = JSON. parseArray (JSON string, type. class);

4. Summary:

Compared with XML, JSON will save traffic and have higher transmission efficiency for mobile devices, especially in the case of poor network environment and traffic restriction.

Reference

Parsing Mode of JSON


Related articles: