不同实体转json教程:通过Gson把json转化为不同类型的实体
程序员文章站
2023-11-13 10:31:34
gsonutils.java
/**
* created by yuanopen on 2018/7/14/014.
*/
public class gsonutils {...
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 需要转化的类型 * @return 返回实体对象 */ public static t josntomodule(string jsonstring, class cls) { t list ; list=gsonutilsgson.fromjson(jsonstring,cls); return list; } /** * @fun 根据不同类型进行实体到json间的转化 * @param cls 需要转化的类型 * @param 需要转化的类型 * @return 返回json字符串 */ public static 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; } }
entitysecond.java:
/** * created by yuanopen on 2018/7/14/014. */ public class entitysecond { 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; } }
测试:
public static void main(string[] args) { 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()); entitysecond second=new entitysecond(); second.setid(2); second.setname("李四"); //moduletojson string secondjson=moduletojosn(second); system.out.println(secondjson); //jsontomudule entitysecond second1= josntomodule(secondjson,entitysecond.class); system.out.println(second1.tostring()); }
结果: