public static <T> Page<T> getPage(Page<T> page,
Map<String, Object> parameter, String path,Class<T> clazz) throws IOException {
if (parameter == null) {
parameter = new HashMap<String, Object>();
}
parameter.put("page", page.getPageNo());
parameter.put("limit", page.getPageSize());
RemoteBean remoteBean = RequestRemoteUtils.getUrlByBean(path,
new HtMap(parameter));
Gson gson = new Gson();
HtPage<T> pageBean = gson.fromJson(remoteBean.getData(),new TypeToken<HtPage<T>>() {
}.getType());
page.setEntities(pageBean.getEntities());
page.setEntityCount(pageBean.getEntityCount());
return page;
}
public class HtPage<T> {
private Collection<T> entities; // 当前页记录
private int entityCount; // 总记录数
public Collection<T> getEntities() {
return entities;
}
public void setEntities(Collection<T> entities) {
this.entities = entities;
}
public int getEntityCount() {
return entityCount;
}
public void setEntityCount(int entityCount) {
this.entityCount = entityCount;
}
}
Gson转换json可以像我这么使用吗,我转换的类型是泛型类型
像我这么写,程序直接报错 java.lang.NullPointerException
------解决思路----------------------
我简单改造了一下:
public class Page<T> {
private Collection<T> entities; // 当前页记录
private int entityCount; // 总记录数
public Collection<T> getEntities() {
return entities;
}
public void setEntities(Collection<T> entities) {
this.entities = entities;
}
public int getEntityCount() {
return entityCount;
}
public void setEntityCount(int entityCount) {
this.entityCount = entityCount;
}
}
定义了一个Pojo
public class People {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "姓名:" + name + ";年龄:" + age;
}
}
测试类改造了:
public class TestGson<T> {
public static void main(String[] args) throws IOException {
// 封装对象
Page<People> peoplePage = new Page<People>();
List<People> pList = new ArrayList<People>();
People p = new People();
p.setName("Tom");
p.setAge(18);
pList.add(p);
peoplePage.setEntities(pList);
peoplePage.setEntityCount(pList.size());
Page<People> newPage = getPage(peoplePage, new HashMap<String, Object>(), "", People.class);
System.out.println(newPage == peoplePage);// false表示是新生成的对象
System.out.println(newPage.getEntities());
}
public static <T> Page<T> getPage(Page<T> page, Map<String, Object> parameter, String path, Class<T> clazz)
throws IOException {
if (parameter == null) {
parameter = new HashMap<String, Object>();
}
parameter.put("page", page.getEntities());
parameter.put("limit", page.getEntityCount());
Gson gson = new Gson();
// 对象转json
String pageStr = gson.toJson(page);
// 直接用这个字符串转对象,注意,这里是生成的新的对象
Page<T> newPage = gson.fromJson(pageStr, new TypeToken<Page<T>>() {
}.getType());
return newPage;
}
}
pom.xml:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
开始用1.5版本会报错