使用GSON对带泛型的对象解析
程序员文章站
2024-03-16 09:32:10
...
可以使用public <T> T fromJson( String json, Type typeOfT ) 方法对带泛型的json串进行解析
Type类型参数书写方式:
new TypeToken<List<User>>(){}.getType()
这里TypeToken<>泛型参数既可以是单个对象类型,也可以是List<T>带泛型list复杂类型
具体示例List带泛型的解析:
//Habby类
public class Habby {
private String name;
private Integer count;
}
//User类
public class User implements Serializable {
private Integer id;
private Integer age;
private String username;
private List<Habby> list;
}
public void fun()
{
List<Habby> listH=new ArrayList<Habby>();
listH.add(new Habby("nan",12));
List<Habby> listH2=new ArrayList<Habby>();
listH2.add(new Habby("ping", 14));
User user=new User(14, "tom", listH);
User user2=new User(15, "jack", listH2);
List<User> listU=new ArrayList<User>();
listU.add(user);
listU.add(user2);
Gson gson=new Gson();
//封装需要转换为json串的List对象
String json = gson.toJson(listU);
System.err.println("json串:");
System.err.println(json);
System.out.println();
//解析json串为指定对象
List<User> list2 = (List<User>)gson.fromJson(json,new TypeToken<List<User>>(){}.getType());
System.err.println("json解析结果:");
for (User user23 : list2) {
System.err.println(user23);
}
}
运行结果:
json串:
[{"age":14,"username":"tom","list":[{"name":"nan","count":12}]},{"age":15,"username":"jack","list":[{"name":"ping","count":14}]}]
User [age=14, username=tom, list=[Habby [name=nan, count=12]]]
User [age=15, username=jack, list=[Habby [name=ping, count=14]]]
下一篇: 算法之递归