資源描述:
《Jackson轉(zhuǎn)換JSON》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、重慶達渝仁科技官網(wǎng):www.cqdyr.comJackson框架Jackson可以輕松的將Java對象轉(zhuǎn)換成json對象和xml文檔,同樣也可以將json、xml轉(zhuǎn)換成Java對象。相比json-lib框架,Jackson所依賴的jar包較少,簡單易用并且性能也要相對高些。而且Jackson社區(qū)相對比較活躍,更新速度也比較快。建議:JSON的轉(zhuǎn)換使用Jackson框架;xml的轉(zhuǎn)換使用xStream框架。1.準備工作1.1.下載依賴庫jar包Jackson的jarall下載地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.
2、jar然后在工程中導入這個jar包即可開始工作官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes因為下面的程序是用junit測試用例運行的,所以還得添加junit的jar包。版本是junit-4.2.8如果你需要轉(zhuǎn)換xml,那么還需要stax2-api.jar1.2.所需要的JavaEntityBirthday:[java]viewplaincopyprint?1.publicclassBirthday{2.3.privateStringbirthday;4.5.publicBirthday(){6.}7.8.publicBirt
3、hday(Stringbirthday){9.this.birthday=birthday;10.}11.12.//getter、setter13.14.@Override15.publicStringtoString(){16.returnthis.birthday;17.}18.}publicclassBirthday{privateStringbirthday;publicBirthday(){}publicBirthday(Stringbirthday){this.birthday=birthday;}//getter、setter@OverridepublicString
4、toString(){returnthis.birthday;}}AccountBean:[java]viewplaincopyprint?1.publicclassAccountBean{2.3.privateintid;重慶達渝仁科技官網(wǎng):www.cqdyr.com1.2.privateStringname;3.4.privateStringemail;5.6.privateStringaddress;7.8.privateBirthdaybirthday;9.10.//getter、setter11.12.@Override13.publicStringtoString(){
5、14.returnthis.name+"#"+this.id+"#"+this.address+"#"+this.birthday+"#"+this.email;15.}16.17.}publicclassAccountBean{privateintid;privateStringname;privateStringemail;privateStringaddress;privateBirthdaybirthday;//getter、setter@OverridepublicStringtoString(){returnthis.name+"#"+this.id+"#"+this.
6、address+"#"+this.birthday+"#"+this.email;}}2.Java對象轉(zhuǎn)換成JSON2.1.JavaBean(Entity/Model)轉(zhuǎn)換成JSON[java]viewplaincopyprint?1.importjava.io.IOException;2.3.importorg.codehaus.jackson.JsonEncoding;4.importorg.codehaus.jackson.JsonGenerator;5.importorg.codehaus.jackson.map.ObjectMapper;6.7.publicclassWr
7、iteEntityJSON{8.publicstaticvoidmain(String[]args){9.AccountBeanbean=newAccountBean();10.bean.setAddress("china-Guangzhou");11.bean.setEmail("hoojo_@126.com");12.bean.setId(1);13.bean.setName("hoojo");14.try{15.ObjectMapperobjectMapper=