使用GSON对带泛型的对象解析

可以使用public T fromJson( String json, Type typeOfT ) 方法对带泛型的json串进行解析

Type类型参数书写方式:

new TypeToken>(){}.getType()

 这里TypeToken<>泛型参数既可以是单个对象类型,也可以是List带泛型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 list;
}


public void fun()
{
    List listH=new ArrayList();
    listH.add(new Habby("nan",12));
		
    List listH2=new ArrayList();
    listH2.add(new Habby("ping", 14));

    User user=new User(14, "tom", listH);
    User user2=new User(15, "jack", listH2);

    List listU=new ArrayList();
    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 list2 = (List)gson.fromJson(json,new TypeToken>(){}.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]]]
		

 

你可能感兴趣的:(Gson转换)