About Java's JSON parsing

What is JSON

JS object notation. As the name suggests (JavaScript Object Notation), it is a lightweight data exchange format.

Object format

         After knowing what JSON is, you have to know how to use it. Here we will not explain all of them in detail, but will talk about a common one. In JSON, a {} represents an object.
         (It can be understood that, in the braces, what is contained is one by oneKey-value pair.)

         Format: use
                  between key and valueColon connection, Used between multiple key-value pairsComma separatedThe
                   key of the key-value pair should be enclosed in quotation marks (usually in Java parsing, the key without quotation marks will report an error. And JS can parse it correctly .) The
                   value of the key-value pair can be in JSAny typeThe data


For example: we write a book, title, introduction

java:

class Book{
    
     
private String name;
private String info;
get/set... 
}
Book b = new Book(); 
b.setName(“金苹果”); 
b.setInfo(“种苹果”);

js:

var b = new Object(); 
b.name = "金苹果"; 
b.info = "种苹果";

XML:

<book>
	<name>金苹果</name> 
	<info>种苹果</info> 
</book>

JSON:

{
    
     
	"name":"金苹果", 
	"info":"种苹果" 
}

The above examples respectively describe the difference when java, js, XML, and JSON describe a piece of information at the same time, but they are still a bit different.

Use of JSON

When we use JSON to parse files, we need to import the jar file package. Next, we will introduce two commonly used JSON, Gson and FastJson, one belongs to Google and the other belongs to Ali.

Use of Gson

first step:

Import gson-2.8.6.jar. The author here provides two download methods.

  1. The author's resource library downloads gson-2.8.6.jar for free .
  2. Download on the open source website https://github.com/google/gson

Insert picture description here

  1. Importing the jar package in IDEA does
    Insert picture description here
    not work now. You still need to click file to open the Project Structure for some configuration of the project. Open Libraries, add the project, and add the gson-2.8.6.jar file package just imported.
    Insert picture description here

The second step:

Write the following code where you need to convert the JSON string:

String json = new Gson().toJSON(要转换的对象);

Example 1: Convert java class code to JSON code
First create a book class and import some commonly used methods.

package kkb.class_code.Leve4_核心类库.Demo8XML与JSON.Gson和FastJson解析;

import java.util.Objects;

public class book {
    
    
    private String id;
    private String name;
    private String 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;
    }

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

package kkb.class_code.Leve4_核心类库.Demo8XML与JSON.Gson和FastJson解析;

import com.google.gson.Gson;

public class Gson1 {
    
    
    public static void main(String[] args) {
    
    
        //1. 创建Gson对象
        Gson g = new Gson();
        //2. 转换
        book b = new book("001","青苹果","种苹果很幸苦");
        String s = g.toJson(b);
        System.out.println(s);
    }
}

result:

{
    
    "id":"001","name":"青苹果","info":"种苹果很幸苦"}

Example 2: Convert JSON code into java classes and collections

package kkb.class_code.Leve4_核心类库.Demo8XML与JSON.Gson和FastJson解析;

import com.google.gson.Gson;

import java.awt.print.Book;
import java.util.HashMap;

public class JSON转java类 {
    
    
    public static void main(String[] args) {
    
    
        //1. 创建Gson对象
        Gson g = new Gson();
        //2. 转换  : {"id":"001","name":"青苹果","info":"种苹果很幸苦"}
        //转为类
        //book b = g.fromJson("{\"id\":\"001\",\"name\":\"青苹果\",\"info\":\"种苹果很幸苦\"}", book.class);
        //System.out.println(b.getName());
        //转为集合
        HashMap data = g.fromJson("{\"id\":\"001\",\"name\":\"青苹果\",\"info\":\"种苹果很幸苦\"}", HashMap.class);
        System.out.println(data.get("name"));


    }
}

result:

青苹果

Use of FastJson

first step:

Import fastjson-1.2.70.jar. The author here also provides two download methods.

  1. The author’s resource library downloads fastjson-1.2.70.jar for free .
  2. Download on the open source website https://github.com/alibaba/fastjson
    Insert picture description here

Insert picture description here
Insert picture description here

The second step:

Write the following code where you need to convert the JSON string:

对象 = new Gson().fromJson(JSON字符串,对象类型.class);

Example 1: Convert java class code to JSON code

package kkb.class_code.Leve4_核心类库.Demo8XML与JSON.Gson和FastJson解析;

import com.alibaba.fastjson.JSON;

public class FastJson转java类 {
    
    
    public static void main(String[] args) {
    
    
        book bk =new book("002","打油诗","从前有座庙,庙里有个和尚");
        //1. 转换
        String json = JSON.toJSONString(bk);
        System.out.println(json);
    }

}

Example 2: Convert JSON code to java class

package kkb.class_code.Leve4_核心类库.Demo8XML与JSON.Gson和FastJson解析;

import com.alibaba.fastjson.JSON;
import kkb.class_code.Leve4_核心类库.Demo8XML与JSON.book.Book;

public class java类转FastJson {
    
    
    public static void main(String[] args) {
    
    
        //1. 转换  {"id":"002","info":"从前有座庙,庙里有个和尚","name":"打油诗"}
        Book bok = JSON.parseObject("{\"id\":\"002\",\"info\":\"从前有座庙,庙里有个和尚\",\"name\":\"打油诗\"}", Book.class);
        System.out.println(bok.getName());
    }

}

result:

002

The above is a brief introduction about the use of JSON. Regarding the use of Gson and FastJson, it depends on personal needs.

Insert picture description here

                                                             <---- About Java's JSON parsing ---->

                                                                              XPATH parses the xml file

                                                                         How to parse XML in IDEA

                                                                         How IDEA debugs

                                                     A very convenient testing method-JUnit unit testing (IDEA)


Guess you like

Origin blog.csdn.net/mjh1667002013/article/details/115054840