由于Java官方并没有给出解析JSON的方式,所以本篇博客主要讲谷歌的GSON和阿里的FastJson。
GSON
- 将对象转换为JSON字符串
String json = new Gson().toJSON(要转换的对象);
- 将JSON字符串转换为对象
对象 = new Gson().fromJson(JSON字符串,对象类型.class);
案例示意:
public class GsonDemo {
public static void main(String[] args) {
Book book = new Book("1001","java");
String json = new Gson().toJson(book);
System.out.println(json);
System.out.println("---------------------------");
Book newBook = new Gson().fromJson(json,Book.class);
System.out.println(newBook);
System.out.println("---------------------------");
HashMap hashMap = new Gson().fromJson("{\"id\":\"1001\",\"name\":\"java\",\"page\":[\"第一页\",\"第二页\",\"第三页\"]}", HashMap.class);
System.out.println(hashMap.get("page"));
System.out.println(hashMap.get("page").getClass());
}
static class Book{
String id;
String name;
public Book(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}
我们发现如果json里面的值是数组时,转换为对象生成的是list格式的对象
FastJson
- 将对象转换为JSON字符串
String json = JSON.toJSONString(要转换的对象);
- 将JSON字符串转换为对象
类型 对象名 = JSON.parseObject(JSON字符串, 类型.class);
或
List<类型> list = JSON.parseArray(JSON字符串,类型.class);
案例示意:
public class Book {
String id;
String name;
public Book(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public Book() {
}
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
public class FastJsonDemo {
public static void main(String[] args) {
Book book = new Book("1001","java");
String fast = JSON.toJSONString(book);
System.out.println(fast);
System.out.println("-------------------");
Book newBook = JSON.parseObject("{\"id\":\"1001\",\"name\":\"java\"}",Book.class);
System.out.println(newBook);
System.out.println("--------------------");
List<String> s = JSON.parseArray("[\"123\",\"456\",\"789\"]", String.class);
System.out.println(s);
}
}
![](https://img-blog.csdnimg.cn/20210411134315919.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3E5NzgwOTAzNjU=,size_16,color_FFFFFF,t_70)
实测Book类中一定要有get方法,否则利用FastJson转换为json字符串为空。
暂时还没有去探究FastJson源码的想法,猜想应该是获取对象属性时利用了get方法。