简介:
jackson是一个流行的基于java的json处理框架
官方wiki:
官方文档:
学习参考:json转换利器gson之实例系列,顺便也学习一下gson
本篇简介如何使用jackson进行java对象与json的互相转换
新建基本student类:
package com.jingshou.pojo; import java.util.date; public class student { private int id; private string name; private date birthday; 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; } public date getbirthday() { return birthday; } public void setbirthday(date birthday) { this.birthday = birthday; } @override public string tostring() { return "student [birthday=" + birthday + ",,]"; } }班级类:
package com.jingshou.pojo; import java.util.list; public class class { private string cname; private list<student> members; public string getcname() { return cname; } public void setcname(string cname) { this.cname = cname; } public list<student> getmembers() { return members; } public void setmembers(list<student> members) { this.members = members; } public string tostring(){ return "the class name is: " + cname + " " + "the members are: " + members; } }测试代码:
package com.jingshou.jackson; import java.io.ioexception; import java.util.arraylist; import java.util.date; import java.util.list; import com.fasterxml.jackson.databind.objectmapper; import com.jingshou.pojo.class; import com.jingshou.pojo.student; public class jacksontest1 { public static void main(string[] args) throws ioexception { student student1 = new student(); student1.setid(5237); student1.setname("jingshou"); student1.setbirthday(new date()); objectmapper mapper = new objectmapper(); // convert object to json string string json = mapper.writevalueasstring(student1); system.out.println("change object to json string: " + json); // convert json string to object student student2 = mapper.readvalue(json, student.class); system.out.println(student2); // create a student list add it to bj student student3 = new student(); student3.setid(5117); student3.setname("saiya"); student3.setbirthday(new date()); list<student> stulist = new arraylist<student>(); stulist.add(student1); stulist.add(student3); class bj = new class(); bj.setcname("五年二班"); bj.setmembers(stulist); string json2 = mapper.writevalueasstring(bj); system.out.println("the json from class is: " + json2); class bj2 = mapper.readvalue(json2, class.class); system.out.println(bj2); } }运行结果:
change object to json string: {"id":5237,"name":"jingshou","birthday":1389513906622} student [birthday=sun jan 12 16:05:06 cst 2014, id=5237, name=jingshou] the json from class is: {"cname":"五年二班","members":[{"id":5237,"name":"jingshou","birthday":1389513906622},{"id":5117,"name":"saiya","birthday":1389513906859}]} the class name is: 五年二班 the members are: [student [birthday=sun jan 12 16:05:06 cst 2014, id=5237, name=jingshou], student [birthday=sun jan 12 16:05:06 cst 2014, id=5117, name=saiya]]小结:
本文出自"lijingshou"博客,请务必保留此出处马开东/blog/2003020