您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java中实体类和JSON对象之间相互转化

2025/3/22 12:14:22发布48次查看
在需要用到json对象封装数据的时候,往往会写很多代码,也有很多复制粘贴,为了用pojo的思想我们可以装json转化为实体对象进行操作
package myutil; import java.io.ioexception; import myproject.student; import myproject.studentlist; import org.codehaus.jackson.map.objectmapper; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; /** * 实体类和json对象之间相互转化(依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar) * @author wck * */ public class jsonutil { /** * 将json转化为实体pojo * @param jsonstr * @param obj * @return */ public static<t> object jsontoobj(string jsonstr,class<t> obj) { t t = null; try { objectmapper objectmapper = new objectmapper(); t = objectmapper.readvalue(jsonstr, obj); } catch (exception e) { e.printstacktrace(); } return t; } /** * 将实体pojo转化为json * @param obj * @return * @throws jsonexception * @throws ioexception */ public static<t> jsonobject objecttojson(t obj) throws jsonexception, ioexception { objectmapper mapper = new objectmapper(); // convert object to json string string jsonstr = ""; try { jsonstr = mapper.writevalueasstring(obj); } catch (ioexception e) { throw e; } return new jsonobject(jsonstr); } public static void main(string[] args) throws jsonexception, ioexception { jsonobject obj = null; obj = new jsonobject(); obj.put("name", "213"); obj.put("age", 27); jsonarray array = new jsonarray(); array.put(obj); obj = new jsonobject(); obj.put("name", "214"); obj.put("age", 28); array.put(obj); student stu = (student) jsontoobj(obj.tostring(), student.class); jsonobject objlist = new jsonobject(); objlist.put("student", array); system.out.println("objlist:"+objlist); studentlist stulist = (studentlist) jsontoobj(objlist.tostring(), studentlist.class); system.out.println("student:"+stu); system.out.println("stulist:"+stulist); system.out.println("#####################################"); jsonobject getobj = objecttojson(stu); system.out.println(getobj); } }
以上所述就是本文的全部内容了,希望大家能够喜欢。
更多java中实体类和json对象之间相互转化。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product