java 与 JSON    

 

 

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;
    }
}
  • 保存信息: toJson(Object src)方法
    import com.google.gson.Gson;
    public class Demo1 {
        public static void main(String[] args) {
            // 创建 Gson 对象
            Gson gson = new Gson();
            Book b = new Book(1001, "book", "info");
            // 将一个对象 b 转换为 json 字符串
            String s = gson.toJson(b);
            System.out.println(s);
        }
    }
    import com.google.gson.Gson;
    import java.util.ArrayList;
    public class Demo2 {
        public static void main(String[] args) {
            // 创建 Gson 对象
            Gson gson = new Gson();
            ArrayListlist = new ArrayList<>();
            list.add("abc");
            list.add(new Book(1001, "book", "info"));
            // 将一个集合 list 转换为 json 字符串
            String s = gson.toJson(list);
            System.out.println(s);
        }
    }
    import com.google.gson.Gson;
    import java.io.*;
    public class Demo3 {
        public static void main(String[] args) throws IOException {
            // 创建 Gson 对象
            Gson gson = new Gson();
            // 将一个复杂的对象转换为字符串
            String s = gson.toJson(new Cabinet("Cabinet",
                    new Book[]{new Book(1001, "book1", "info1"),
                            new Book(1002, "book2", "info2"),
                            new Book(1003, "book3", "info3")}, "张三"));
            // 将获得的字符串写入文件中
            FileWriter fw = new FileWriter("cabinet.json");
            fw.write(s);
            fw.close(); // 记得关闭流!
        }
    }
    • 将一个复杂的对象用 json 格式保存到文件中
    • 将一个集合保存为 json 格式
    • 将一个类保存为 json 格式
  • 提取信息: fromJson(String json, Class
    • 从文件中提取一个较为复杂的类
    • 提取一个数组
    • 提取一个类

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

2.FastJSON

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

  • 保存信息: toJSONString(Object object)方法
    注意:使用 FastJSON 保存的类每个属性必须有 get 方法,否则无法保存。上面的 Book 类没有提供 get 方法,则无法保存。
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args) {
            // 假设这个类有提供 get 方法
            Book b = new Book(1001, "book", "info");
            // 转化为 JSON 字符串
            String s = JSON.toJSONString(b);
            // 打印出来检查是否正确
            System.out.println(s);
        }
    }
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args) {
            // 假设 Book 类有提供 get 方法
            Book[] b = new Book[]{new Book(1001, "book", "info"), new Book(1002, "abc", "ofni")};
            String s = JSON.toJSONString(b);
            System.out.println(s);
        }
    }
    import com.alibaba.fastjson.JSON;
    import java.io.FileWriter;
    import java.io.IOException;
    public class Demo {
        public static void main(String[] args) throws IOException {
            Book b1 = new Book(1001, "1", "a");
            Book b2 = new Book(1002, "2", "b");
            Book b3 = new Book(1003, "3", "c");
            Book[] bs = {b1, b2, b3};
            Cabinet c = new Cabinet("cabinet", bs, "abc");
            String json = JSON.toJSONString(c);
            FileWriter fw = new FileWriter("cabinet2.json");
            fw.write(json);
            fw.close();
        }
    }
    • 保存一个较为复杂的类到文件中
    • 保存一个集合(数组)的信息
    • 保存一个类的信息
  • 获取信息: parseObject(String text, Class
    • 从文件中获取一个较为复杂的对象
    • 获取一个数组信息
    • 获取一个类的信息