JSON introduction and parsing of JSON in java

Keywords: Java Back-end

1, JSON overview

  • JSON refers to JavaScript Object Notation
  • JSON is a lightweight text data exchange format
  • JSON is language independent: JSON uses Javascript syntax to describe data objects, but JSON is still language and platform independent. The JSON parser and JSON library support many different programming languages. At present, many dynamic (PHP, JSP,. NET) programming languages support JSON.
  • JSON is self descriptive and easier to understand

2, JSON syntax

1. Grammar rules

  • Data in name / value pair
  • Data is separated by commas
  • Braces {} save object
  • Brackets [] hold arrays, which can contain multiple objects

2. Name / key value pair

       key:value

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

       The key of the key value pair should be enclosed in quotation marks (generally, when the key is parsed in Java, an error will be reported if the key does not use quotation marks, but JS can parse correctly)         
                        "key must be a string"        
       The value of a key value pair can be any type of data in JS.

"name" : "Zhang San"

3. JSON object

JSON objects are written in {}

An object represented by a brace.
         The attributes of the object are described in parentheses. The properties of an object are described by key value pairs
         (it can be understood that braces contain key value pairs.)

{
    "name":"Zhang San",
    "info":"lawyer"
}

4. JSON array

JSON arrays are written in brackets []:

The array can contain multiple objects:

[
    { key1 : value1-1 , key2:value1-2 }, 
    { key1 : value2-1 , key2:value2-2 }, 
    { key1 : value3-1 , key2:value3-2 }, 
    ...
    { keyN : valueN-1 , keyN:valueN-2 }, 
]

An array can be nested within an object, such as:

{
    "sites": [
        { "name":"Zhang San" , "lawyer" }, 
        { "name":"Li Si" , "judge" }, 
        { "name":"Xiao Ming" , "student" }
    ]
}

5. Boolean and null values of JSON

When the value of JSON is Boolean or null, it is not enclosed in quotation marks

{ "flag":true }


{ "name":null }

3, JSON parsing

This time, only two JSON parsing methods in java are introduced: Gson (Google) and FastJSON (ALI).

1,Gson

  • Convert object to JSON string

Conversion steps:

        1. Import jar package, download address: GitHub - google/gson: A Java serialization/deserialization library to convert Java Objects into JSON and backhttps://github.com/google/gson/         2. Write the following code where the JSON string needs to be converted:

String json = new Gson().toJSON(Object to convert);

Example:

import com.google.gson.Gson;

public class Demo {
    public static void main(String[] args) {
        //1. Create a Gson object
        Gson g = new Gson();
        //2. Conversion
        Book b = new Book(100, "language", "first grade");
        String s = g.toJson(b);
        System.out.println(s);
    }

}



/**
*Book class
*
*/
import java.util.Objects;

public class Book {
    private int id;
    private String name;
    private String info;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return id == book.id &&
                Objects.equals(name, book.name) &&
                Objects.equals(info, book.info);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, info);
    }

    public Book(int id, String name, String info) {
        this.id = id;
        this.name = name;
        this.info = info;
    }

    public Book() {
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 JSON strings to objects

Conversion steps:

         1. Cited as JAR package

        2. Where Java objects need to be converted, write the following code:

object = new Gson().fromJson(Json String, object type.class);

Example: (note that escape is required in the string)

import com.google.gson.Gson;

import java.util.HashMap;

public class Demo3 {
    public static void main(String[] args) {
        //1. Create a Gson object
        Gson g = new Gson();
        //2. Conversion
        HashMap data = g.fromJson("{\"id\":100,\"name\":\"language\",\"info\":\"second grade\"}", HashMap.class);
        System.out.println(data.get("name"));

    }

}

2,FastJson

  • Convert object to JSON string

Conversion steps:

        1. Import JAR package, download address:

GitHub - alibaba/fastjson: A fast JSON parser/generator for Java.A fast JSON parser/generator for Java. . Contribute to alibaba/fastjson development by creating an account on GitHub.https://github.com/alibaba/fastjson/         2. Write the following code where the JSON string needs to be converted:

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

Example:

import com.alibaba.fastjson.JSON;

public class demo {
    public static void main(String[] args) {
        Book book = new Book(2002,"mathematics","Calculus");
        //transformation
        String string = JSON.toJSONString(book);
        System.out.println(string);
    }
}


/**
*Book class
*
*/

import java.util.Objects;

public class Book {
    private int id;
    private String name;
    private String info;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return id == book.id &&
                Objects.equals(name, book.name) &&
                Objects.equals(info, book.info);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, info);
    }

    public Book(int id, String name, String info) {
        this.id = id;
        this.name = name;
        this.info = info;
    }

    public Book() {
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 JSON strings to objects

Conversion steps:

        1. Introducing JAR packages

         2. At the location of the java object to be converted, write the following code:

 Type object name = JSON.parseObject(JSON String, type.class);

Example:

import com.alibaba.fastjson.JSON;

import java.util.List;

public class demo3 {
    public static void main(String[] args) {

        //Conversion ["sldfjldf","sldf","sjjsj"]
        List<String> s = JSON.parseArray("[\"sldfjldf\",\"sldf\",\"sjjsj\"]", String.class);
        System.out.println(s.get(1));


    }
}

Posted by DragonHighLord on Tue, 30 Nov 2021 17:50:18 -0800