带泛型的json转换

前言

jackson的类库很多,有google的Gson,有马云的fastJson,还有spring boot用的fasterxml,等等,还有很多。这里使用google的Gson,介绍带有泛型的bean转换。

  1. 普通转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//定义一个bean
public class UserResponse{

private String username;

...getter and setter
}

@Test
public void test(){
Gson json = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String jsonStr="{\"username\":\"foo\"}";
UserResponse userResponse = json.fromJson(jsonStr,UserResponse.class);
}
  1. 带泛型转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Response<T>{

private String code;
private String desc;
private T response;

...getter and setter


public class UserResponse{
private String username;

...getter and setter
}

@Test
public void test(){
Gson json = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String jsonStr="{\"code\": \"100\",\"desc\": \"成功\",\"response\": {\"username\": \"foo\"}}";
  Response<UserResponse> response = json.fromJson(jsonStr,new TypeToken<Response<UserResponse>>(){}.getType());
}