GsonUtils.java
/**
* Created by yuanopen on 2018/7/14/014.
*/
public class GsonUtils {
private static Gson GsonUtilsGson = new Gson();
/**
* @fun 根据不同类型进行json到实体间的转化
* @param jsonString json字符串
* @param cls 需要转化的类型
* @param <T> 需要转化的类型
* @return 返回实体对象
*/
public static <T> T josnToModule(String jsonString, Class<T> cls) {
T list ;
list=GsonUtilsGson.fromJson(jsonString,cls);
return list;
}
/**
* @fun 根据不同类型进行实体到json间的转化
* @param cls 需要转化的类型
* @param <T> 需要转化的类型
* @return 返回Json字符串
*/
public static <T> String ModuleTojosn(T cls) {
return GsonUtilsGson.toJson(cls);
}
}
实体:
EntityOne.java:
/**
* Created by yuanopen on 2018/7/14/014.
*/
public class EntityOne {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "id:"+id+" name:"+name;
}
}
Demo
EntityOne one=new EntityOne();
one.setId(1);
one.setName("张三");
//moduleTojson
String oneJson=ModuleTojosn(one);
System.out.println(oneJson);
//jsonTomudule
EntityOne one1= josnToModule(oneJson,EntityOne.class);
System.out.println(one1.toString());