例子使用的gson版本:2.8.5
package com.lpx.demo.gson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class GsonTypeToken {
private Integer id;
private String name;
public GsonTypeToken(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Type type = TypeToken.getParameterized(List.class, GsonTypeToken.class).getType();
List<GsonTypeToken> list = new ArrayList();
GsonTypeToken t1 = new GsonTypeToken(1, "a");
GsonTypeToken t2 = new GsonTypeToken(2, "b");
list.add(t1);
list.add(t2);
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
list.clear();
list = gson.fromJson(json, type);
for (GsonTypeToken g : list) {
System.out.println("id:" + g.getId() + " , name:" + g.getName());
}
}
}
网友评论