在需要用到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); } }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
使用json.net的方法
如何把对象转换成json格式
以上就是实体类与json对象转化方法总结的详细内容。
