1.介绍
Fastjson是阿里巴巴公司基于Java语言开发的高性能且功能完善的JSON操作类库,目前fastjson有两个版本,一个是Fastjson,另外一个是fastjson2 。
- Fastjson1 的JSONObject 只是简单实现Map接口,是无序的map容器
- Fastjson2 的JSONObject 实现了链结构的Map,是有序的Map容器
- 无论是JSONObject或者JSONArray都摆脱了JSON的类,而且JSON由抽象类——>接口
我这里选择使用fastjson2
2.依赖
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.12</version>
</dependency>
3.操作jJSON对象的方法
创建一个实体,别忘了导入lombok
@Data
public class BookModel {
private String id;
private String language;
private String edition;
private String author;
}
案例
public static void main(String[] args) {
String json = "{\n" +
" \"id\":1,\n" +
" \"language\":\"java\",\n" +
" \"edition\":\"one\",\n" +
" \"author\":\"张三\"\n" +
"}";
final BookModel model = JSONObject.parseObject(json, BookModel.class);
System.out.println(model.getId()+"\t"+model.getLanguage());
}
4.操作数组
操作数组有两个方法
public static void main(String[] args) {
String json = "[\n" +
" {\n" +
" \"id\":1,\n" +
" \"language\":\"java\",\n" +
" \"edition\":\"one\",\n" +
" \"author\":\"张三\"\n" +
" },\n" +
" {\n" +
" \"id\":2,\n" +
" \"language\":\"C++\",\n" +
" \"edition\":\"two\",\n" +
" \"author\":\"李四\"\n" +
" }\n" +
"]";
//方法一
List<BookModel> modelList = JSON.parseObject(json, new TypeReference<List<BookModel>>() {});
for (BookModel bookModel : modelList) {
System.out.println(bookModel.getId()+"\t"+bookModel.getLanguage());
}
//方法二
modelList = JSON.parseArray(json, BookModel.class);
for (BookModel bookModel : modelList) {
System.out.println(bookModel.getId()+"\t"+bookModel.getLanguage());
}
}