89、【JavaEE】【JSON】JSON

2021-10-04  本文已影响0人  yscyber

1、概述

2、JSON 结构

{
    "id": "1234",
    "name": "张三",
    "type": 1
}
{
    "arr": [
        {
            "id": "1234",
            "name": "张三"
        },
        {
            "id": "5678",
            "name": "李四"
        }
    ]
}

3、作为数据交换格式

3.1、JSON 作为数据交换最经典的场景:

JSON-1

3.2、Java 对象与 JSON 转换

3.3、Fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>

使用com.alibaba.fastjson.JSON类的public static String toJSONString(Object object)方法。

public class Person {

    private String name;

    private String gender;

    private Integer age;

    public Person() {}

    public Person(String name, String gender, Integer age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}
import com.alibaba.fastjson.JSON;
import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {
        Person person = new Person("张三", "男", 20);

        String jsonString = JSON.toJSONString(person);

        System.out.println(jsonString);
        // {"age":20,"gender":"男","name":"张三"}
    }

}
public class Person {

    private String name;

    private String gender;

    private Integer age;

    private Integer[] arr;

    public Person() {}

    public Person(String name, String gender, Integer age, Integer[] arr) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.arr = arr;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer[] getArr() {
        return arr;
    }

    public void setArr(Integer[] arr) {
        this.arr = arr;
    }

}
import com.alibaba.fastjson.JSON;
import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {
        Person person = new Person("张三", "男", 20, new Integer[]{1, 2, 3});

        String jsonString = JSON.toJSONString(person);

        System.out.println(jsonString);
        // {"age":20,"arr":[1,2,3],"gender":"男","name":"张三"}
    }

}
public class CourseGrade {

    private String courseName;

    private Integer courseGrade;

    public CourseGrade() {}

    public CourseGrade(String courseName, Integer courseGrade) {
        this.courseName = courseName;
        this.courseGrade = courseGrade;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Integer getCourseGrade() {
        return courseGrade;
    }

    public void setCourseGrade(Integer courseGrade) {
        this.courseGrade = courseGrade;
    }

}
public class Person {

    private String name;

    private String gender;

    private Integer age;

    private CourseGrade[] courseGradeArr;

    public Person() {}

    public Person(String name, String gender, Integer age, CourseGrade[] courseGradeArr) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.courseGradeArr = courseGradeArr;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public CourseGrade[] getCourseGradeArr() {
        return courseGradeArr;
    }

    public void setCourseGradeArr(CourseGrade[] courseGradeArr) {
        this.courseGradeArr = courseGradeArr;
    }

}
import com.alibaba.fastjson.JSON;
import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {

        CourseGrade courseGrade1 = new CourseGrade("Java", 100);
        CourseGrade courseGrade2 = new CourseGrade("Vue.js", 98);
        CourseGrade courseGrade3 = new CourseGrade("MySQL", 85);

        Person person = new Person("张三", "男", 20, new CourseGrade[]{courseGrade1, courseGrade2, courseGrade3});

        String jsonString = JSON.toJSONString(person);

        System.out.println(jsonString);
        // {"age":20,"courseGradeArr":[{"courseGrade":100,"courseName":"Java"},{"courseGrade":98,"courseName":"Vue.js"},{"courseGrade":85,"courseName":"MySQL"}],"gender":"男","name":"张三"}
    }

}

注解@JSONField的作用是:在 Java 对象转为 JSON 的时候,使用该注解,自定义字段的名称进行输出,并控制字段的排序,还可以决定字段是否进行序列化。

name:字段的名称
ordinal:字段的顺序,越小的排在前面
serialize:字段是否序列化(是否转换为 JSON),true参与序列化,false不参与序列化

import com.alibaba.fastjson.annotation.JSONField;

public class CourseGrade {

    @JSONField(name = "Course-Name", ordinal = 0, serialize = true)
    private String courseName;

    @JSONField(name = "Course-Grade", ordinal = 1, serialize = true)
    private Integer courseGrade;

    public CourseGrade() {}

    public CourseGrade(String courseName, Integer courseGrade) {
        this.courseName = courseName;
        this.courseGrade = courseGrade;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Integer getCourseGrade() {
        return courseGrade;
    }

    public void setCourseGrade(Integer courseGrade) {
        this.courseGrade = courseGrade;
    }

}
import com.alibaba.fastjson.annotation.JSONField;

public class Person {

    @JSONField(name = "Name", ordinal = 0, serialize = true)
    private String name;

    @JSONField(name = "Gender", ordinal = 1, serialize = true)
    private String gender;

    @JSONField(name = "Age", serialize = false)
    private Integer age;

    @JSONField(name = "Course-Grade-List", ordinal = 2, serialize = true)
    private CourseGrade[] courseGradeArr;

    public Person() {}

    public Person(String name, String gender, Integer age, CourseGrade[] courseGradeArr) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.courseGradeArr = courseGradeArr;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public CourseGrade[] getCourseGradeArr() {
        return courseGradeArr;
    }

    public void setCourseGradeArr(CourseGrade[] courseGradeArr) {
        this.courseGradeArr = courseGradeArr;
    }

}
import com.alibaba.fastjson.JSON;
import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {

        CourseGrade courseGrade1 = new CourseGrade("Java", 100);
        CourseGrade courseGrade2 = new CourseGrade("Vue.js", 98);
        CourseGrade courseGrade3 = new CourseGrade("MySQL", 85);

        Person person = new Person("张三", "男", 20, new CourseGrade[]{courseGrade1, courseGrade2, courseGrade3});

        String jsonString = JSON.toJSONString(person);

        System.out.println(jsonString);
        // {"Name":"张三","Gender":"男","Course-Grade-List":[{"Course-Name":"Java","Course-Grade":100},{"Course-Name":"Vue.js","Course-Grade":98},{"Course-Name":"MySQL","Course-Grade":85}]}
    }

}

使用com.alibaba.fastjson.JSON类的public static <T> T parseObject(String text, Class<T> clazz)方法。

成功转换的前提是,必须有setter/getter

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Person {

    private String myName;

    private String myGender;

}
import com.alibaba.fastjson.JSON;

import com.yscyber.json.one.Person;

import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {
        String jsonStr = "{'myName': '张三', 'myGender': '男'}";

        Person person = JSON.parseObject(jsonStr, Person.class);
        System.out.println(person); // Person(myName=张三, myGender=男)
    }

}

@JSONField中的name属性:

import com.alibaba.fastjson.annotation.JSONField;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Person {

    @JSONField(name = "x")
    private String myName;

    @JSONField(name = "y")
    private String myGender;

}
import com.alibaba.fastjson.JSON;

import com.yscyber.json.one.Person;

import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {
        String jsonStr = "{'x': '张三', 'y': '男'}";

        Person person = JSON.parseObject(jsonStr, Person.class);
        System.out.println(person); // Person(myName=张三, myGender=男)
    }

}

自动忽略大小写、“下划线”转“驼峰”:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Person {

    private String myName;

    private String myGender;

}
import com.alibaba.fastjson.JSON;

import com.yscyber.json.one.Person;

import org.junit.Test;

public class JsonTest {

    @Test
    public void test1() {
        String jsonStr = "{'my_name': '张三', 'my_gender': '男'}";

        Person person = JSON.parseObject(jsonStr, Person.class);
        System.out.println(person); // Person(myName=张三, myGender=男)
    }

}

3.4、JavaScript 关于 JSON 的处理

object JSON.parse(string):JSON 字符串转 JavaScript 对象;
string JSON.stringify(object):JavaScript 对象转 JSON 字符串;

    let obj = JSON.parse("{\"name\": \"张三\", \"age\": 20}");
    console.log(obj);
    console.log(typeof obj);

    let str = JSON.stringify(obj);
    console.log(str);
    console.log(typeof str);

注意:object JSON.parse(string)中的参数,JSON 字符串中不能含有单引号:

let jsonStr = "{\"name\": \"张三\", \"age\": 20}"; //正确,内部使用转义字符

let jsonStr = '{"name": "张三", "age": 20}'; // 正确,因为使用单引号包裹可以,内部可以直接使用双引号,无需转义

let jsonStr = "{'name': '张三', 'age': 20}"; // 错误
上一篇下一篇

猜你喜欢

热点阅读