Java第四十二天,Json

一、概念

全称 JavaScrlipt object Notation,译为Javascript对象表示法;Json是存储和交换文本信息的语法。类似XML,但比XML更小、更快,更易解析

二、语法

1.基本规则

  • JSON 数据是由键值对构成的
  • JSON的键可以用 引号(单双均可)引起来,也可以不用引号
  • JSON的值的取值类型如下:
  1. 数字(整数或浮点数)
  2. 字符串(在双引号中)
  3. 逻辑值(true | false)
  4. 数组([...])
  5. 对象({...})
  6. null
  • 多个键值对由逗号分隔
  • 花(大)括号保存对象
  • 方括号表示数组

2.示例

let person = {"name": "张三", age: 23, 'gender': true};
let persons = {
    "persons": [
        {"name": "张三", "age": 23, "gender": true},
        {"name": "李四", "age": 24, "gender": true},
        {"name": "王五", "age": 25, "gender": false}
    ]
};
let persons = [
	{"name": "张三", "age": 23, "gender": true},
	{"name": "李四", "age": 24, "gender": true},
	{"name": "王五", "age": 25, "gender": true}
];

3.如何通过 JSON 对象获取数据

  • Json对象.键名
  • Json对象[“键名”]
  • Json数组对象[索引值]

三、Json 对象和 Java 对象之间的相互转换

1.Json对象 转 Java对象

(1)常见解析器

  • Jsonlib
  • Gson
  • fastjson
  • jackson

(2)jackson 的使用

Java实体类

package web.entil;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Student {

    private String name;
    private String sex;
    private Integer age;

    // @JsonIgnore 忽略该属性,禁止转换 json
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

Json 转 Java 核心代码

package web.entil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class Test {

    public static void main(String[] args) {

        // 创建 Java 实体类对象
        Student student = new Student();
        student.setName("张三");
        student.setSex("男");
        student.setAge(20);
        student.setBirthday(new Date());

        // 创建 Jackson 核心对象
        ObjectMapper mapper = new ObjectMapper();


        String stuStr = null;
        try {
            stuStr = mapper.writeValueAsString(student);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Student stu = new Student();
        /*
        Java 对象转 Json 对象需要用到 Jackson 的 readValue 方法
        参数1:原 Json 字符串
        参数2:目的 Java 实体类 字节码文件
         */
        try {
            stu = mapper.readValue(stuStr, Student.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(stu);

    }
}

2.Java对象 转 Json对象

(1)常见解析器

  • Jsonlib
  • Gson
  • fastjson
  • jackson

(2)jackson 的使用

// jackson jar依赖包

https://download.csdn.net/download/ITlanyue/12726758

①基本使用

Java 实体类

package web.entil;

public class Student {

    private String name;
    private String sex;
    private Integer age;


    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

Java 转换 Json 核心代码

package web.entil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    public static void main(String[] args) {

        // 创建 Java 实体类对象
        Student student = new Student();
        student.setName("张三");
        student.setSex("男");
        student.setAge(20);

        // 创建 Jackson 核心对象
        ObjectMapper mapper = new ObjectMapper();

        /*
         * 转换
         * writeValue(参数1,obj)
         * 参数1:
         * 		File:将obj对象转换为JSON字符串,并保存到指定的文件中
         * 		Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
         * 		OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
         *
         * writeValueAsString(Object obj) ===> 将对象转换为字符串
         *
         * writeValueAs...(Object obj) ===> 将对象转换为...
         */
        String stuStr = null;
        try {
            stuStr = mapper.writeValueAsString(student);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        System.out.println(stuStr);

    }
}

②注解使用

注意:

可以应用于属性或者对应的 getter 方法上

@JsonIgnore ===> 排除属性;对应属性将不会被转换为字符串

@JsonFormat ===> 对属性值进行格式化,指明期望类型

Java 实体类

package web.entil;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Student {

    private String name;
    private String sex;
    private Integer age;
    
    // @JsonIgnore 忽略该属性,禁止转换 json
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

Java 转 Json 核心代码

package web.entil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Date;

public class Test {

    public static void main(String[] args) {

        // 创建 Java 实体类对象
        Student student = new Student();
        student.setName("张三");
        student.setSex("男");
        student.setAge(20);
        student.setBirthday(new Date());

        // 创建 Jackson 核心对象
        ObjectMapper mapper = new ObjectMapper();

        /*
         * 转换
         * writeValue(参数1,obj)
         * 参数1:
         * 		File:将obj对象转换为JSON字符串,并保存到指定的文件中
         * 		Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
         * 		OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
         *
         * writeValueAsString(Object obj) ===> 将对象转换为字符串
         *
         * writeValueAs...(Object obj) ===> 将对象转换为...
         */
        String stuStr = null;
        try {
            stuStr = mapper.writeValueAsString(student);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        System.out.println(stuStr);

    }
}

 

posted @ 2020-08-19 10:49  IT蓝月  阅读(143)  评论(0编辑  收藏  举报
Live2D