JSON 是不同程序之间传递信息的一种格式。本文描述了 JSON 在 Java 中的应用。
目前 Java 中比较主流的相关解析工具有谷歌提供的 Gson 和阿里提供的 FastJSON 。
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,
}
}
使用 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;
}
}
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();
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);
}
}
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(); // 记得关闭流!
}
}
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 字符串中没有对应类中的属性,那么对应的类的这个属性设置为默认值。
使用 FastJSON 提取或保存 json 字符串方法:
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();
}
}
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"));
}
}
原文:https://www.cnblogs.com/lgxblogs/p/java_JSON.html