java 与 JSON

时间:2021-05-25 09:06:56   收藏:0   阅读:20

Java 与 JSON

JSON 是不同程序之间传递信息的一种格式。本文描述了 JSON 在 Java 中的应用。
目前 Java 中比较主流的相关解析工具有谷歌提供的 Gson 和阿里提供的 FastJSON 。

一、JSON 格式

JSON: JavaScript Object Notation(JS对象简谱),是一种轻量级的数据交换格式。
例如一本书,有 id 属性值为 "1001",有 name 属性值为 "book",有 info 属性值为 "简介",用 JSON 表示如下:

{
  "id":"1001",
  "name":"book",
  "info":"简介"
}

另外,JSON 格式中还可以包含数组(用中括号包含[,,,]),对象之间还可以互相嵌套。
例如一个柜子,名字是 "书柜",有一个 "books" 属性包含了三本书,还有一个 belong 属性表示属于某个人,可以表示为:

{
  "name":"书柜",
  "books":["book1","book2",{
    "id":"1001",
    "name":"book",
    "info":"简介"
  }],
  "belong":{
    "name":"张三",
    "age":18,
  }
}

二、Java 与 JSON

1. Gson

使用 Gson 类可以提取一串包含 JSON 的字符串中的信息,也可以将一个类的信息保存到一串 JSON 字符串中。
后面代码使用 Book 类和 Cabinet 类如下

class Book {
    private int id;
    private String name;
    private String info;
    public String toString() {
        return "name:" + name + ", info:" + info;
    }
}
class Cabinet {
    private String name;
    private Book[] books;
    private String belong;
    public String toString() {
        return "Cabinet{" +
                "name=‘" + name + ‘\‘‘ +
                ", books=" + Arrays.toString(books) +
                ", belong=‘" + belong + ‘\‘‘ +
                ‘}‘;
    }
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cabinet cabinet = (Cabinet) o;
        return Objects.equals(name, cabinet.name) && Arrays.equals(books, cabinet.books) && Objects.equals(belong, cabinet.belong);
    }
    public int hashCode() {
        int result = Objects.hash(name, belong);
        result = 31 * result + Arrays.hashCode(books);
        return result;
    }
    public Cabinet() {
    }
    public Cabinet(String name, Book[] books, String belong) {
        this.name = name;
        this.books = books;
        this.belong = belong;
    }
}

注意:JSON 字符串应该对应好对应类的各个属性名,如果 JSON 字符串中出现了对应类中没有的属性名,那么这个属性将被忽略。同理,如果 JSON 字符串中没有对应类中的属性,那么对应的类的这个属性设置为默认值。

2.FastJSON

使用 FastJSON 提取或保存 json 字符串方法:

原文:https://www.cnblogs.com/lgxblogs/p/java_JSON.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!