java的Jackson框架实现轻易转换JSON
jackson可以轻松的将java对象转换成json对象和xml文档,同样也可以将json、xml转换成java对象。
相比json-lib框架,jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且jackson社区相对比较活跃,更新速度也比较快。
一、准备工作
1、 下载依赖库jar包
jackson的jar all下载地址:
然后在工程中导入这个jar包即可开始工作
官方示例:http://wiki.fasterxml.com/jacksoninfiveminutes
因为下面的程序是用junit测试用例运行的,所以还得添加junit的jar包。版本是junit-4.2.8
如果你需要转换xml,那么还需要stax2-api.jar
2、 测试类基本代码如下
package com.hoo.test; import java.io.ioexception; import java.io.stringwriter; import java.util.arraylist; import java.util.hashmap; import java.util.iterator; import java.util.linkedhashmap; import java.util.list; import java.util.map; import java.util.set; import org.codehaus.jackson.jsonencoding; import org.codehaus.jackson.jsongenerationexception; import org.codehaus.jackson.jsongenerator; import org.codehaus.jackson.jsonparseexception; import org.codehaus.jackson.map.jsonmappingexception; import org.codehaus.jackson.map.objectmapper; import org.codehaus.jackson.node.jsonnodefactory; import org.codehaus.jackson.xml.xmlmapper; import org.junit.after; import org.junit.before; import org.junit.test; import com.hoo.entity.accountbean; /** * <b>function:</b>jackson 将java对象转换成json字符串,也可以将json字符串转换成java对象 * jar-lib-version: jackson-all-1.6.2 * jettison-1.0.1 * @author hoojo * @file jacksontest.java * @package com.hoo.test * @project spring3 * @version 1.0 */ @suppresswarnings("unchecked") public class jacksontest { private jsongenerator jsongenerator = null; private objectmapper objectmapper = null; private accountbean bean = null; @before public void init() { bean = new accountbean(); bean.setaddress("china-guangzhou"); bean.setemail("hoojo_@126.com"); bean.setid(1); bean.setname("hoojo"); objectmapper = new objectmapper(); try { jsongenerator = objectmapper.getjsonfactory().createjsongenerator(system.out, jsonencoding.utf8); } catch (ioexception e) { e.printstacktrace(); } } @after public void destory() { try { if (jsongenerator != null) { jsongenerator.flush(); } if (!jsongenerator.isclosed()) { jsongenerator.close(); } jsongenerator = null; objectmapper = null; bean = null; system.gc(); } catch (ioexception e) { e.printstacktrace(); } } }
3、 所需要的javaentity
package com.hoo.entity; public class accountbean { private int id; private string name; private string email; private string address; private birthday birthday; //getter、setter @override public string tostring() { return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email; } }
birthday
package com.hoo.entity; public class birthday { private string birthday; public birthday(string birthday) { super(); this.birthday = birthday; } //getter、setter public birthday() {} @override public string tostring() { return this.birthday; } }
二、java对象转换成json
1、 javabean(entity/model)转换成json
/** * function:将java对象转换成json字符串 * @author hoojo */ @test public void writeentityjson() { try { system.out.println("jsongenerator"); //writeobject可以转换java对象,eg:javabean/map/list/array等 jsongenerator.writeobject(bean); system.out.println(); system.out.println("objectmapper"); //writevalue具有和writeobject相同的功能 objectmapper.writevalue(system.out, bean); } catch (ioexception e) { e.printstacktrace(); } }
运行后结果如下:
jsongenerator {"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"} objectmapper {"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":hoojo_@126.com}
上面分别利用jsongenerator的writeobject方法和objectmapper的writevalue方法完成对java对象的转换,二者传递的参数及构造的方式不同;jsongenerator的创建依赖于objectmapper对象。也就是说如果你要使用jsongenerator来转换json,那么你必须创建一个objectmapper。但是你用objectmapper来转换json,则不需要jsongenerator。
objectmapper的writevalue方法可以将一个java对象转换成json。这个方法的参数一,需要提供一个输出流,转换后可以通过这个流来输出转换后的内容。或是提供一个file,将转换后的内容写入到file中。当然,这个参数也可以接收一个jsongenerator,然后通过jsongenerator来输出转换后的信息。第二个参数是将要被转换的java对象。如果用三个参数的方法,那么是一个config。这个config可以提供一些转换时的规则,过指定的java对象的某些属性进行过滤或转换等。
2、 将map集合转换成json字符串
/** * <b>function:</b>将map转换成json字符串 * @author hoojo */ @test public void writemapjson() { try { map<string, object> map = new hashmap<string, object>(); map.put("name", bean.getname()); map.put("account", bean); bean = new accountbean(); bean.setaddress("china-beijin"); bean.setemail("hoojo@qq.com"); map.put("account2", bean); system.out.println("jsongenerator"); jsongenerator.writeobject(map); system.out.println(""); system.out.println("objectmapper"); objectmapper.writevalue(system.out, map); } catch (ioexception e) { e.printstacktrace(); } }
转换后结果如下:
jsongenerator {"account2":{"address":"china-beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo", "account":{"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}} objectmapper {"account2":{"address":"china-beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo", "account":{"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":hoojo_@126.com}}
3、 将list集合转换成json
/** * <b>function:</b>将list集合转换成json字符串 * @author hoojo */ @test public void writelistjson() { try { list<accountbean> list = new arraylist<accountbean>(); list.add(bean); bean = new accountbean(); bean.setid(2); bean.setaddress("address2"); bean.setemail("email2"); bean.setname("haha2"); list.add(bean); system.out.println("jsongenerator"); //list转换成json字符串 jsongenerator.writeobject(list); system.out.println(); system.out.println("objectmapper"); //用objectmapper直接返回list转换成的json字符串 system.out.println("1###" + objectmapper.writevalueasstring(list)); system.out.print("2###"); //objectmapper list转换成json字符串 objectmapper.writevalue(system.out, list); } catch (ioexception e) { e.printstacktrace(); } }
结果如下:
jsongenerator [{"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}] objectmapper 1###[{"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}] 2###[{"address":"china-guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
外面就是多了个[]中括号;同样array也可以转换,转换的json和上面的结果是一样的,这里就不再转换了。~.~
4、下面来看看jackson提供的一些类型,用这些类型完成json转换;如果你使用这些类型转换json的话,那么你即使没有javabean(entity)也可以完成复杂的java类型的json转换。下面用到这些类型构建一个复杂的java对象,并完成json转换。
@test public void writeothersjson() { try { string[] arr = { "a", "b", "c" }; system.out.println("jsongenerator"); string str = "hello world jackson!"; //byte jsongenerator.writebinary(str.getbytes()); //boolean jsongenerator.writeboolean(true); //null jsongenerator.writenull(); //float jsongenerator.writenumber(2.2f); //char jsongenerator.writeraw("c"); //string jsongenerator.writeraw(str, 5, 10); //string jsongenerator.writerawvalue(str, 5, 5); //string jsongenerator.writestring(str); jsongenerator.writetree(jsonnodefactory.instance.pojonode(str)); system.out.println(); //object jsongenerator.writestartobject();//{ jsongenerator.writeobjectfieldstart("user");//user:{ jsongenerator.writestringfield("name", "jackson");//name:jackson jsongenerator.writebooleanfield("sex", true);//sex:true jsongenerator.writenumberfield("age", 22);//age:22 jsongenerator.writeendobject();//} jsongenerator.writearrayfieldstart("infos");//infos:[ jsongenerator.writenumber(22);//22 jsongenerator.writestring("this is array");//this is array jsongenerator.writeendarray();//] jsongenerator.writeendobject();//} accountbean bean = new accountbean(); bean.setaddress("address"); bean.setemail("email"); bean.setid(1); bean.setname("haha"); //complex object jsongenerator.writestartobject();//{ jsongenerator.writeobjectfield("user", bean);//user:{bean} jsongenerator.writeobjectfield("infos", arr);//infos:[array] jsongenerator.writeendobject();//} } catch (exception e) { e.printstacktrace(); } }
运行后,结果如下:
jsongenerator "agvsbg8gd29ybgqgamfja3nvbie=" true null 2.2c world jac worl "hello world jackson!" "hello world jackson!" {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]} {"user":{"address":"address","name":"haha","id":1,"birthday":null,"email":"email"},"infos":["a","b","c"]}
怎么样?构造的json字符串和输出的结果是一致的吧。关键看懂用jsongenerator提供的方法,完成一个object的构建。
三、json转换成java对象
1、 将json字符串转换成javabean对象
@test public void readjson2entity() { string json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}"; try { accountbean acc = objectmapper.readvalue(json, accountbean.class); system.out.println(acc.getname()); system.out.println(acc); } catch (jsonparseexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
很简单,用到了objectmapper这个对象的readvalue这个方法,这个方法需要提供2个参数。第一个参数就是解析的json字符串,第二个参数是即将将这个json解析吃什么java对象,java对象的类型。当然,还有其他相同签名方法,如果你有兴趣可以一一尝试使用方法,当然使用的方法和当前使用的方法大同小异。运行后,结果如下:
haha haha#1#address#null#email
2、 将json字符串转换成list<map>集合
/** * <b>function:</b>json字符串转换成list<map> * @author hoojo */ @test public void readjson2list() { string json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]"; try { list<linkedhashmap<string, object>> list = objectmapper.readvalue(json, list.class); system.out.println(list.size()); for (int i = 0; i < list.size(); i++) { map<string, object> map = list.get(i); set<string> set = map.keyset(); for (iterator<string> it = set.iterator();it.hasnext();) { string key = it.next(); system.out.println(key + ":" + map.get(key)); } } } catch (jsonparseexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
尝试过将上面的json转换成list,然后list中存放accountbean,但结果失败了。但是支持map集合。因为你转成list.class,但是不知道list存放何种类型。只好默然map类型。因为所有的对象都可以转换成map结合,运行后结果如下:
2 address:address2 name:haha2 id:2 email:email2 address:address name:haha id:1 email:email
3、 json字符串转换成array数组,由于上面的泛型转换不能识别到集合中的对象类型。所有这里用对象数组,可以解决这个问题。只不过它不再是集合,而是一个数组。当然这个不重要,你可以用arrays.aslist将其转换成list即可。
/** * <b>function:</b>json字符串转换成array * @author hoojo */ @test public void readjson2array() { string json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]"; try { accountbean[] arr = objectmapper.readvalue(json, accountbean[].class); system.out.println(arr.length); for (int i = 0; i < arr.length; i++) { system.out.println(arr[i]); } } catch (jsonparseexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
运行后的结果:
2 haha2#2#address2#null#email2 haha#1#address#null#email
4、 json字符串转换成map集合
/** * <b>function:</b>json字符串转换map集合 * @author hoojo */ @test public void readjson2map() { string json = "{\"success\":true,\"a\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ "\"b\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}"; try { map<string, map<string, object>> maps = objectmapper.readvalue(json, map.class); system.out.println(maps.size()); set<string> key = maps.keyset(); iterator<string> iter = key.iterator(); while (iter.hasnext()) { string field = iter.next(); system.out.println(field + ":" + maps.get(field)); } } catch (jsonparseexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
运行后结果如下:
3 success:true a:{address=address2, name=haha2, id=2, email=email2} b:{address=address, name=haha, id=1, email=email}
四、jackson对xml的支持
jackson也可以完成java对象到xml的转换,转换后的结果要比json-lib更直观,不过它依赖于stax2-api.jar这个jar包。
/** * <b>function:</b>java对象转换成xml文档 * 需要额外的jar包 stax2-api.jar * @author hoojo */ @test public void writeobject2xml() { //stax2-api-3.0.2.jar system.out.println("xmlmapper"); xmlmapper xml = new xmlmapper(); try { //javabean转换成xml //xml.writevalue(system.out, bean); stringwriter sw = new stringwriter(); xml.writevalue(sw, bean); system.out.println(sw.tostring()); //list转换成xml list<accountbean> list = new arraylist<accountbean>(); list.add(bean); list.add(bean); system.out.println(xml.writevalueasstring(list)); //map转换xml文档 map<string, accountbean> map = new hashmap<string, accountbean>(); map.put("a", bean); map.put("b", bean); system.out.println(xml.writevalueasstring(map)); } catch (jsongenerationexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
运行上面的方法,结果如下:
xmlmapper <unknown><address>china-guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown> <unknown><unknown><address>china-guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown> <email><address>china-guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></email></unknown> <unknown><a><address>china-guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></a> <b><address>china-guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></b></unknown>
看结果,根节点都是unknown 这个问题还没有解决,由于根节点没有转换出来,所有导致解析xml到java对象,也无法完成。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
java的Jackson将json字符串转换成泛型List
-
java的Jackson框架实现轻易转换JSON
-
Java实现Json字符串与Object对象相互转换的方式总结
-
java中用ObjectMapper类实现Json与bean的转换示例
-
java中用ObjectMapper类实现Json与bean的转换示例
-
java实现Xml与json之间的相互转换操作示例
-
Java实现Json字符串与Object对象相互转换的方式总结
-
使用谷歌Gson实现Json数据与Java对象、List、Map之间的相互转换笔记
-
《Jackson 框架,轻易转换JSON》学习笔记
-
Java高效实现xml转换json的一种方法