目前前后端分离是越来越趋势化了,前后端交互一般都是用json数据格式,前端传一堆json数据过来,我们转化就成了一个问题,下面就根据转化为实体类和List相关做了一个案例:
首先使用的jar版本是:基本用的都是最新的版本:
net.sf.json-lib
json-lib
2.2.3
jdk15
com.google.code.gson
gson
2.8.5
com.alibaba
fastjson
1.2.58
com.fasterxml.jackson.core
jackson-core
2.9.9
对比的主类是:
public class JSONCompare {
public static void main(String[] args) {
toBean();
toList();
}
private static void toList() {
String json = "[\n" +
" {\n" +
" \"id\": \"124545721\",\n" +
" \"age\": \"23\",\n" +
" \"name\": \"张三\"\n" +
" },\n" +
" {\n" +
" \"id\": \"14545454\",\n" +
" \"age\": \"88\",\n" +
" \"name\": \"李四\"\n" +
" }\n" +
"]";
FastJsonUtil.toList(json);
System.out.println("------------------>>");
GsonUtil.toList(json);
System.out.println("------------------>>");
JacksonUtil.toList(json);
System.out.println("------------------>>");
JsonLibUtil.toList(json);
System.out.println("------------------>>");
}
public static void toBean(){
String json = "{\n" +
" \"name\": \"张三\",\n" +
" \"id\": \"23\",\n" +
" \"startTime\": \"1561904000000\",\n" +
" \"endTime\": \"2018-02-01 06:06:06\"\n" +
"}";
FastJsonUtil.toBean(json);
System.out.println("------------------>>");
GsonUtil.toBean(json);
System.out.println("------------------>>");
JsonLibUtil.toBean(json);
System.out.println("------------------>>");
JacksonUtil.toBean(json);
System.out.println("\n\n时间格式都改成yyyy-HH-dd hh:mm:ss----------------->>");
String json1 = "{\n" +
" \"name\": \"张三\",\n" +
" \"id\": \"23\",\n" +
" \"startTime\": \"2022-02-01 09:09:09\",\n" +
" \"endTime\": \"2018-02-01 06:06:06\"\n" +
"}";
FastJsonUtil.toBean(json1);
System.out.println("------------------>>");
GsonUtil.toBean(json1);
System.out.println("------------------>>");
JsonLibUtil.toBean(json1);
System.out.println("------------------>>");
JacksonUtil.toBean(json1);
System.out.println("\n\n参数缺失,并有多余参数加入------------------>>");
String json2 = "{\n" +
" \"name\": \"张三\",\n" +
" \"age\": \"23\",\n" +
"}";
FastJsonUtil.toBean(json2);
System.out.println("------------------>>");
GsonUtil.toBean(json2);
System.out.println("------------------>>");
JsonLibUtil.toBean(json2);
System.out.println("------------------>>");
JacksonUtil.toBean(json2);
System.out.println("\n\nList开始------------------>>");
}
}
调用不同json格式的类最后再展示:先运行一下结果:
时间:470ms使用fastJson转化成实体:Y(name=张三, id=23, startTime=Sun Jun 30 22:13:20 CST 2019, endTime=Thu Feb 01 06:06:06 CST 2018)
------------------>>
使用Gson装化成实体失败:com.google.gson.JsonSyntaxException: 1561904000000
------------------>>
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
时间:519msJsonLib转化成实体:Y(name=张三, id=23, startTime=Mon Jul 01 22:59:12 CST 2019, endTime=Mon Jul 01 22:59:12 CST 2019)
------------------>>
使用Jackson转化成实体失败:com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2018-02-01 06:06:06": not a valid representation (error: Failed to parse Date value '2018-02-01 06:06:06': Cannot parse date "2018-02-01 06:06:06": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
at [Source: (String)"{
"name": "张三",
"id": "23",
"startTime": "1561904000000",
"endTime": "2018-02-01 06:06:06"
}"; line: 5, column: 16] (through reference chain: com.timeblog.common.Y["endTime"])
时间格式都改成yyyy-HH-dd hh:mm:ss----------------->>
时间:0ms使用fastJson转化成实体:Y(name=张三, id=23, startTime=Tue Feb 01 09:09:09 CST 2022, endTime=Thu Feb 01 06:06:06 CST 2018)
------------------>>
时间:3ms使用Gson装化成实体:Y(name=张三, id=23, startTime=Tue Feb 01 09:09:09 CST 2022, endTime=Thu Feb 01 06:06:06 CST 2018)
------------------>>
时间:7msJsonLib转化成实体:Y(name=张三, id=23, startTime=Mon Jul 01 22:59:13 CST 2019, endTime=Mon Jul 01 22:59:13 CST 2019)
------------------>>
使用Jackson转化成实体失败:com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-02-01 09:09:09": not a valid representation (error: Failed to parse Date value '2022-02-01 09:09:09': Cannot parse date "2022-02-01 09:09:09": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
at [Source: (String)"{
"name": "张三",
"id": "23",
"startTime": "2022-02-01 09:09:09",
"endTime": "2018-02-01 06:06:06"
}"; line: 4, column: 18] (through reference chain: com.timeblog.common.Y["startTime"])
参数缺失,并有多余参数加入------------------>>
时间:0ms使用fastJson转化成实体:Y(name=张三, id=null, startTime=null, endTime=null)
------------------>>
使用Gson装化成实体失败:com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 4 column 2 path $.null
------------------>>
时间:0msJsonLib转化成实体:Y(name=张三, id=null, startTime=null, endTime=null)
------------------>>
使用Jackson转化成实体失败:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "age" (class com.timeblog.common.Y), not marked as ignorable (4 known properties: "endTime", "name", "startTime", "id"])
at [Source: (String)"{
"name": "张三",
"age": "23",
}"; line: 3, column: 13] (through reference chain: com.timeblog.common.Y["age"])
List开始------------------>>
时间:5ms使用fastJson转化成List:[X(id=124545721, age=23, name=张三), X(id=14545454, age=88, name=李四)]
------------------>>
时间:7ms使用Gson装化成List:[X(id=124545721, age=23, name=张三), X(id=14545454, age=88, name=李四)]
------------------>>
时间:19ms使用Jackson装化成List:[X(id=124545721, age=23, name=张三), X(id=14545454, age=88, name=李四)]
------------------>>
时间:8msJsonLib转化成List:[X(id=124545721, age=23, name=张三), X(id=14545454, age=88, name=李四)]
------------------>>
(1)、Gson不能转化时间戳为Date类型
(2)、Json-lib会把时间类型赋值为当前时间
(3)、Jackson转化时间类型出错
(4)、Jackson实体类的字段和json字符串中的key要一直,否则出错
(5)、Gson缺失类对应的变量并多出其他数据会报错
(6)、FastJson几乎可以满足这些要求
(7)、转化为List时候FastJson> Gson>JsonLib>Jackson
(8)、Json-lib最近都没有新版本问题很大不建议使用
(9)、如果使用FastJson的时候转成嵌套的实体时:
这样使用:否则里面的X不会转过去,用X获取数据就会报错
AtencentBaseResBean = JSON.parseObject(result, new TypeReference>(){});
其他三个可以根据实际情况选择性使用,各有各的优点,如果不怎么在乎性能可以直接使用fastjson,很强大,但是性能肯定有影响的。
其他类源码:
1、FastJsonUtil.java
import java.util.ArrayList;
import java.util.List;
public class JacksonUtil {
public static void toBean(String json) {
try {
Long start = System.currentTimeMillis();
ObjectMapper mapper = new ObjectMapper();
Y y = mapper.readValue(json, Y.class);
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Jackson转化成实体:" + y.toString());
} catch (Exception e) {
System.out.println("使用Jackson转化成实体失败:" + e);
}
}
public static void toList(String json){
try{
Long start = System.currentTimeMillis();
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, X.class);
List list = mapper.readValue(json, javaType);
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Jackson装化成List:" + list.toString());
}catch (Exception e){
System.out.println("使用Jackson装化成List失败:" + e);
}
}
}
2、GsonUtil.java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
public class GsonUtil {
public static void toBean(String json) {
try {
Long start = System.currentTimeMillis();
Gson gson = new Gson();
Y y = gson.fromJson(json, Y.class);
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Gson装化成实体:" + y.toString());
} catch (Exception e) {
System.out.println("使用Gson装化成实体失败:" + e);
}
}
public static void toList(String json){
try{
Long start = System.currentTimeMillis();
Gson gson = new Gson();
List list = gson.fromJson(json, new TypeToken>() {}.getType());
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Gson装化成List:" + list.toString());
}catch (Exception e){
System.out.println("使用Gson装化成List失败:" + e);
}
}
}
3、JacksonUtil.java
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class JacksonUtil {
public static void toBean(String json) {
try {
Long start = System.currentTimeMillis();
ObjectMapper mapper = new ObjectMapper();
Y y = mapper.readValue(json, Y.class);
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Jackson转化成实体:" + y.toString());
} catch (Exception e) {
System.out.println("使用Jackson转化成实体失败:" + e);
}
}
public static void toList(String json){
try{
Long start = System.currentTimeMillis();
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, X.class);
List list = mapper.readValue(json, javaType);
Long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start) + "ms使用Jackson装化成List:" + list.toString());
}catch (Exception e){
System.out.println("使用Jackson装化成List失败:" + e);
}
}
}
4、JsonLibUtil.java
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.List;
public class JsonLibUtil {
public static void toBean(String json) {
try {
Long start = System.currentTimeMillis();
JSONObject jsonObject = JSONObject.fromObject(json);
Y y = (Y) JSONObject.toBean(jsonObject, Y.class);
Long end = System.currentTimeMillis();
System.out.println("时间:"+(end - start) +"msJsonLib转化成实体:" + y.toString());
} catch (Exception e) {
System.out.println("JsonLib转化成实体失败:" + e);
}
}
public static void toList(String json) {
try {
Long start = System.currentTimeMillis();
List list=(List) JSONArray.toList(JSONArray.fromObject(json), X.class);
Long end = System.currentTimeMillis();
System.out.println("时间:"+(end - start) +"msJsonLib转化成List:" + list.toString());
} catch (Exception e) {
System.out.println("JsonLib转化成List失败:" + e);
}
}
}
5、X.java
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class X {
private Long id;
private Integer age;
private String name;
}
6、Y.java
@Data
@ToString
public class Y {
private String name;
private Long id;
private Date startTime;
private Date endTime;
}
《………………………………………………菜鸟起飞中,请各位走过路过的多多指教……………………………………》