java 与 JSON

Posted ——light

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)方法
    • 将一个类保存为 json 格式
    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);
        }
    }
    
    • 将一个集合保存为 json 格式
    import com.google.gson.Gson;
    import java.util.ArrayList;
    public class Demo2 {
        public static void main(String[] args) {
            // 创建 Gson 对象
            Gson gson = new Gson();
            ArrayList<Object> list = new ArrayList<>();
            list.add("abc");
            list.add(new Book(1001, "book", "info"));
            // 将一个集合 list 转换为 json 字符串
            String s = gson.toJson(list);
            System.out.println(s);
        }
    }
    
    • 将一个复杂的对象用 json 格式保存到文件中
    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(); // 记得关闭流!
        }
    }
    
  • 提取信息: fromJson(String json, Class classOfT)方法
    • 提取一个类
    import com.google.gson.Gson;
    public class Demo4 {
      public static void main(String[] args) {
        Gson gson = new Gson();
        // {"name":"book","info":"abc"}
        Book book = gson.fromJson("{\\"name\\":\\"book\\",\\"info\\":\\"abc\\"}", Book.class);
        System.out.println(book);
      }
    }
    
    • 提取一个数组
    import com.google.gson.Gson;
    import java.util.List;
    public class Demo5 {
      public static void main(String[] args) {
        // ["abc","bcd","cde"]
        List list = new Gson().fromJson("[\\"abc\\",\\"bcd\\",\\"cde\\"]",List.class);
        for (Object s : list) {
          System.out.println(s);
        }
      }
    }
    
    • 从文件中提取一个较为复杂的类
    import com.google.gson.Gson;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    public class Demo6 {
        public static void main(String[] args) throws IOException {
            // 此处使用的文件为上面代码中保存的 cabinet.json 文件
            // 读取文件中的数据
            BufferedReader br = new BufferedReader(new FileReader("cabinet.json"));
            String s = br.readLine();
            br.close(); // 别忘记关闭!
            // 创建 Gson 对象
            Gson gson = new Gson();
            // 如果我们没有 Cabinet 这个类,则可以转化为 HashMap 对象
            HashMap hashMap = gson.fromJson(s, HashMap.class);
            // 打印全部
            System.out.println(hashMap);
            List<Book> list = (List<Book>) hashMap.get("books");
            // 打印 books
            System.out.println(list.get(1));
        }
    }
    

注意: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 clazz)方法
    注意:获取信息的类必须提供 无参构造方法和各个 set 方法,否则会出现 JSONException 异常
    • 获取一个类的信息
    import com.alibaba.fastjson.JSON;
    public class Demo {
        public static void main(String[] args){
            // {"id":1001,"name":"b","info":"1"}
            Book b = JSON.parseObject("{\\"id\\":1001,\\"name\\":\\"b\\",\\"info\\":\\"1\\"}", Book.class);
            System.out.println(b);
        }
    }
    
    • 获取一个数组信息
    import com.alibaba.fastjson.JSON
    import java.io.IOException;
    import java.util.List;
    public class Demo {
        public static void main(String[] args) {
            // ["",{"id":123,"name":"abc"},null]
            List list = (List) JSON.parse("[\\"\\",{\\"id\\":123,\\"name\\":\\"abc\\"},null]");
            System.out.println(list.get(1));
        }
    }
    
    • 从文件中获取一个较为复杂的对象
    import com.alibaba.fastjson.JSON;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.List;
    public class Demo {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("cabinet2.json"));
            String s = br.readLine();
            HashMap hashMap = JSON.parseObject(s, HashMap.class);
            System.out.println(hashMap);
            List list = (List) hashMap.get("books");
            System.out.println(list.get(1));
            HashMap book2 = JSON.parseObject(list.get(1).toString(), HashMap.class);
            System.out.println(book2.get("name"));
        }
    }
    

以上是关于java 与 JSON的主要内容,如果未能解决你的问题,请参考以下文章

json 个人的vscode的代码片段

java 代码片段

GraphQL 片段 JSON 格式

我无法在片段中加载数据 json

实用代码片段将json数据绑定到html元素 (转)

json 可视代码工作室Angular with Firebase片段