JavaWeb speed pass JSON

Table of contents

1. Quick Start with JSON

        1.Basic introduction: 

        2. Define the format: 

        3. Getting Started Case: 

2. Conversion between JSON objects and strings

        1. Commonly used methods: 

        2. Application examples: 

        3. Usage details: 

3. Use of JSON in Java

        1.Basic instructions: 

        2. Application scenarios: 

            2.1 JSON <---> JavaBean

            2.2 JSON <---> List

            2.3 JSON <---> Map


1. Quick Start with JSON

        1.Basic introduction: 

        (1) The full name of JSON is "JavaScript Object Notation" , which is JavaScript object notation.

        (2) JSON is a lightweight text data exchange format and is widely used;

        (3) JSON is independent of language , that is, Java, PHP, asp.net, etc. can all use JSON.

        2. Define the format: 

        The definition format of JSON is similar to the format of defining objects through {} in JS. Note that the key in JSON must be enclosed in double quotes "", and the value can be of type string, number, object, array, true, false, or null . details as follows--

        var variable name = {

                "key1" : value,

                "key2" : value,

                "key3" : [], //JSON array

                "key4" : {}, //JSON can define objects nested in objects

                "key5" : [{}, {}, {}] //JSON object array (no restriction on type [ weak ])

        }

        3. Getting Started Case: 

                The intro.html code is as follows: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Json introduction</title>
</head>
    <script type="text/javascript">
        window.onload = function () {
            //定义一个JSON对象
            var student = {
                "name" : "Cyan",
                "age" : 21,
                "gender" : "male",
                "hobby" : ["basketball", "writing", "chess"],
                "goals" : [{"kyrie" : "irving"}, {"Cyan" : "RA9"}, 141, 450]
            }

            //取出JSON对象中的值(加号+ 仅取出值)
            console.log("name = ", student.name);
            console.log("name = " + student.name);

            console.log("hobby = ", student.hobby);
            for (var i = 0; i < student.hobby.length; ++i) {
                console.log("The no.%i hobby = ", (i + 1), student.hobby[i]);
            }

            console.log("goals = " + student.goals)
            console.log("goals = ", student.goals)
            console.log("score of goals = ", student.goals[3])
            console.log("Cyan of obj of goals = ", student.goals[1].Cyan)
        }
    </script>
<body bgcolor="#e0ffff">
    <h2 style="color: pink">请查看控制台打印出的信息捏~</h2>
</body>
</html>

                running result: 


2. Conversion between JSON objects and strings

        1. Commonly used methods: 

        (1) JSON.stringify(json) - Convert a JSON object to a json string.

        (2) JSON.parse(jsonString) - Convert a json string into a JSON object.

        PS: JSON is a JS built-in object (built-in) . As shown below: 

        2. Application examples: 

                The string_json.html code is as follows: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>string_json</title>
    <script type="text/javascript">
        //加载页面
        window.onload = function() {
            console.log("=================== JSON --> String ===================")
            //定义一个JSON对象
            var jsonCyan = {
                "name" : "Cyan",
                "token" : "RA9"
            }
            console.log("jsonCyan = ", jsonCyan);
            console.log("jsonCyan's type = ", typeof(jsonCyan));

            //将JSON对象转换为String类型
            var strCyan = JSON.stringify(jsonCyan);
            console.log("strCyan = ", strCyan)
            console.log("strCyan's type = ", typeof(strCyan));

            console.log("\n=================== String --> JSON ===================")
            var strFive = "{\"name\":\"Five\",\"token\":\"5\"}";
            var jsonFive = JSON.parse(strFive);
            console.log("strFive = ", strFive)
            console.log("jsonFive = ", jsonFive)
        }
    </script>
</head>
<body>
</body>
</html>

                operation result: 

        3. Usage details: 

        (1) The JSON.stringify(json) method will not affect the original json object; the JSON.parse(string) method will not affect the original string.

        (2) When defining a JSON object, attributes can use either double quotes "" or single quotes '' ; but when converting native strings into JSON objects through the parse method, the attributes must use double quotes "" , otherwise Will keep reporting errors.

        (3) The string obtained by the JSON.stringify(json) method defaults to a string represented by double quotes "". If the syntax format is correct, it can be directly converted into a JSON object.


3. Use of JSON in Java

        1.Basic instructions: 

        To use JSON in Java, you need to introduce a third-party jar package - gson.jar . This jar package is a Java class library provided by Google for mapping between Java objects and JSON data. gson.jar can convert JSON strings and Java objects to and from each other.

        Import gson.jar as follows: 

       2. Application scenarios: 

            2.1 JSON <---> JavaBean

                Define a JavaBean student class. The Student class code is as follows: 

package javabean;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 */
public class Student {
    private String name;
    private double scores;

    public Student() {
    }
    public Student(String name, double scores) {
        this.name = name;
        this.scores = scores;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScores() {
        return scores;
    }

    public void setScores(double scores) {
        this.scores = scores;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", scores=" + scores +
                '}';
    }
}

                The JavaJSON class code is as follows: 

package javaObject;

import com.google.gson.Gson;
import javabean.Student;

public class JavaJSON {
    public static void main(String[] args) {
        //首先创建一个Gson对象
        Gson gson = new Gson();

        Student cyan = new Student("Cyan", 450.0);

        //利用Gson对象的toJson方法,将JavaBean --> JSON字符串
        String strCyan = gson.toJson(cyan);
        System.out.println("strCyan = " + strCyan);

        //利用Gson对象的fromJson方法,将JSON字符串 --> JavaBean对象
            //需要传入一个符合JSON格式的字符串,以及JavaBean类的Class对象
            //底层用到了反射机制
        Student student = gson.fromJson(strCyan, Student.class);
        System.out.println("student = " + student);
    }
}

                operation result: 

            2.2 JSON <---> List

                The JavaJSON2 class code is as follows: 

package javaObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javabean.Student;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JavaJSON2 {
    public static void main(String[] args) {
        Gson gson = new Gson();

        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Cyan", 450));
        studentList.add(new Student("Five", 456));

        //List --> Json字符串
        String strList = gson.toJson(studentList);
        System.out.println("strList = " + strList);

        //Json字符串 --> List
        Type type = new TypeToken<List<Student>>() {}.getType();
        System.out.println("\ntype = " + type);
        System.out.println("type's type = " + type.getClass());
        List<Student> students = gson.fromJson(strList, type);
            /*
                (1) 由于TypeToken的无参构造器使用protected访问修饰符修饰,
                    因此无法直接在别包下直接调用该无参构造。
                (2) 解决之道————借助匿名内部类,匿名内部类有自己隐式的无参构造,
                    而该无参构造中又默认隐含super关键字,借此调用TypeToken的无参构造。
                (3) TypeToken无参构造器底层用到了反射机制(拿到了类的正名)。
             */
        System.out.println("\nstudents = " + students);
    }
}

                operation result : 

            2.3 JSON <---> Map

                The JavaJSON3 class code is as follows: 

package javaObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javabean.Student;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 */
public class JavaJSON3 {
    public static void main(String[] args) {
        Gson gson = new Gson();

        Map<Integer, Student> studentMap = new HashMap<>();
        studentMap.put(1, new Student("Cyan", 450));
        studentMap.put(2, new Student("Rain", 445));

        //Map --> JSON字符串
        String strMap = gson.toJson(studentMap);
        System.out.println("strMap = " + strMap);

        //JSON字符串 --> Map
        Type type = new TypeToken<Map<Integer, Student>>() {}.getType();
        Map<Integer, Student> students = gson.fromJson(strMap, type);
        System.out.println("students = " + students);
    }
}

                operation result: 

        System.out.println("END-------------------------------------------------------------");

Guess you like

Origin blog.csdn.net/TYRA9/article/details/132547303