JSON: JavaScript Object Notation, 即JS对象简谱,是一种轻量级的数据交换格式。
JSON格式
{
"name":"张三".
"age":18,
"friends":["李四","王二",{
"name":"麻子",
"age":"20"
}]
}
JSON解析的两种方式
1. Gson
-
将对象转换为JSON字符串:
String json = new Gson().toJson(对象名);
-
将JSON字符串转换为对象:
类名 对象名 = new Gson().fromJson(JSON字符串, 类名.class);
注意:数组[…]会转为ArrayList集合
e.g.
public static void main(String[] args){
// 1. 创建Gson对象
Gson g = new Gson();
// 2. 转换
Book b = new Book("100", "金苹果", "种植苹果真辛苦");
String s = g.toJson(b);
}
public static void main(String[] args){
// 1. 创建Gson对象
Gson g = new Gson();
// 2. 转换
String s = "{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}";
Book b = g.fromJson(s, Book.class); // 1
HashMap data = g.fromJson(s, HashMap.class); // 2
}
2. Fastjson
-
将对象转换为JSON字符串:
String json = JSON.toJSONString(对象名);
-
将JSON字符串转换为对象:
类名 对象名 = JSON.parseObject(JSON字符串, 类名.class);
-
将JSON字符串转换为ArrayList:
List<类名> list = JSON.parseArray(JSON字符串, 类名.class);
e.g.
public static void main(String[] args){
// 1. 转换
Book b = new Book("100", "金苹果", "种植苹果真辛苦");
String s = JSON.toJSONString(book);
}
public static void main(String[] args){
// Object
String s = "{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}";
Book b = JSON.parseObject(s, Book.class);
// ArrayList
String s1 = "[\"一二三\",\"四五六\",\"七八九\"]";
List<String> strings = JSON.parseArray(s1, String.class);
}