FASTJSON v2是FASTJSON项目的重要升级,目标是为下一个十年提供一个高性能的JSON库。通过同一套API,
GitHub地址 : https://github.com/alibaba/fastjson2
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.3</version>
</dependency>
如果原来使用fastjson 1.2.x版本,可以使用兼容包,兼容包不能保证100%兼容,请仔细测试验证,发现问题请及时反馈。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.3</version>
</dependency>
package com.janson.demo.fastjson;
import lombok.Data;
/**
* @Author Janson
* @Date 2022/5/16 9:05
* @Version 1.0
*/
@Data
public class DemoData {
private Integer id;
private String name;
private Integer age;
private String sex;
}
package com.janson.demo.fastjson;
import com.alibaba.fastjson2.JSON;
import java.util.List;
/**
* @Author Janson
* @Date 2022/5/16 9:03
* @Version 1.0
*/
public class TestFastjson {
public static void main(String[] args) {
System.out.println("-----JSON.toJSONString()-----测试javaBean转为json字符串---------------");
DemoData demoData = new DemoData();
demoData.setAge(18);
demoData.setId(11108);
demoData.setName("法外狂徒张三");
demoData.setSex("男"); //
String stoJSONString = JSON.toJSONString(demoData);
System.out.println(stoJSONString);
System.out.println("-----------测试结束--------------\n");
System.out.println("-----JSON.parseObject(s, DemoData.class);-----测试json字符串转为javaBean---------------");
DemoData demoDataparseObject = JSON.parseObject(stoJSONString, DemoData.class);
System.out.println(demoDataparseObject.getAge() + " " + demoDataparseObject.getName()+" " + demoDataparseObject.getId() + " "+demoDataparseObject.getSex());
System.out.println("-----------测试结束--------------\n");
System.out.println("-----JSON.parseArray(str, DemoData.class);-----测试一组json字符串转为javaBean的集合(list)---------------");
String str = "[{\"age\":18,\"id\":11108,\"name\":\"法外狂徒张三\",\"sex\":\"男\"},{\"age\":80,\"id\":188808,\"name\":\"法外狂徒川普\",\"sex\":\"未知\"}]";
List<DemoData> demoDataparseArray = JSON.parseArray(str, DemoData.class);
int i = 0;
for (DemoData demoDataList: demoDataparseArray) {
System.out.println("集合索引:" + i+ "集合数据" + demoDataList);
i++;
}
System.out.println("-----------测试结束--------------");
}
}
System.out.println("-----JSONB.toBytes()-----测试javaBean序列化JSONB,字节数组--------------");
DemoData demoData1 = new DemoData();
demoData1.setAge(18);
demoData1.setId(11108);
demoData1.setName("法外狂徒张三");
demoData1.setSex("男");
byte[] bytes = JSONB.toBytes(demoData1);
System.out.println(bytes.length);
for (int b = 0;b<bytes.length;b++) {
System.out.println( b +" "+ bytes[b]);
}
System.out.println("-----------测试结束--------------\n");
System.out.println("-----JSONB.parseObject(bytes,DemoData.class)-----测试JSONB解析为javaBean--------------");
DemoData demoDataJSONB = JSONB.parseObject(bytes,DemoData.class);
System.out.println(demoDataJSONB.getId() + " "+ demoDataJSONB.getName() + " "
+ demoDataJSONB.getAge() + " "+demoDataJSONB.getSex());
System.out.println("-----------测试结束--------------\n");
``