Jackson implements cross-transfer of object objects to JSON strings

Source: Internet
Author: User

During the development of a project, data interaction is essential when the client responds to the server. However, data interaction through JSON became part of our development, and Jackson provided a good mechanism for our JSON transformation. I'll use the examples below to summarize how to use Jackson.

First, prepare

If you need to use Jackson, you have to import the appropriate rack package with the following three packages

Jackson-annotations;jackson-core;jackson-databind

Maven introduces dependency code

<span style= "FONT-SIZE:18PX;" ><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId> Jackson-databind</artifactid><version>2.0.6</version></dependency><dependency> <groupid>com.fasterxml.jackson.module</groupid><artifactid>jackson-module-jaxb-annotations </artifactId><version>2.0.6</version></dependency><dependency><groupId> Com.fasterxml.jackson.core</groupid><artifactid>jackson-core</artifactid><version> 2.3.0</version></dependency><dependency><groupid>com.fasterxml.jackson.core</ groupid><artifactid>jackson-annotations</artifactid><version>2.3.0</version></ Dependency></span>

Two, non-date object entities and JSON mutual transfer

1. Define Entity Userbean.java,deptbean.java

<span style= "FONT-SIZE:18PX;" >package Com.jackson.bean;import Java.util.list;public class Deptbean {private int deptid;private String deptName; Private list<userbean> userbeanlist;public int Getdeptid () {return deptid;} public void Setdeptid (int deptid) {this.deptid = DeptID;} Public String Getdeptname () {return deptname;} public void Setdeptname (String deptname) {this.deptname = Deptname;} Public list<userbean> getuserbeanlist () {return userbeanlist;} public void Setuserbeanlist (list<userbean> userbeanlist) {this.userbeanlist = userbeanlist;} @Overridepublic string toString () {String userbeanliststring = ""; for (UserBean userbean:userbeanlist) {userbeanliststr ing + = userbean.tostring () + "\ n";} Return "Deptbean [deptid=" + DeptID + ", deptname=" + deptname+ ", \nuserbeanliststring=" + userbeanliststring + "]";} Public Deptbean (int deptid, String deptname, list<userbean> userbeanlist) {super (); this.deptid = DeptID; This.deptname = deptname;this.userbeanlist = userBeanlist;} Public Deptbean () {super ();}} </span>

<span style= "FONT-SIZE:18PX;" >package Com.jackson.bean;public class UserBean {private int userid;private string username;private string password; Private String email;public int getUserId () {return userId;} public void Setuserid (int userId) {this.userid = userId;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} @Overridepublic String toString () {return "UserBean [userid=" + UserId + ", username=" + username+ ", password=" + passwor D + ", email=" + email + "]";} Public UserBean (int userId, string userName, string password, string email) {super (); This.userid = Userid;this.username = Username;this.password = Password;this.email = email;} Public UserBean () {super ();}} </span>
Note: There must be no parameter construction method in the entity, otherwise the conversion will have the following exception;

<span style= "FONT-SIZE:18PX;" >com.fasterxml.jackson.databind.jsonmappingexception:no suitable constructor found for type [Simple Type, class Com.jackson.bean.UserBean]: Can not instantiate from JSON object (need to add/enable type information?) </span>

2.jackson Data Conversion Tool class

<span style= "FONT-SIZE:18PX;" >package Com.jackson.utils;import Com.fasterxml.jackson.core.type.typereference;import com.fasterxml.jackson.databind.objectmapper;/** * The Class Jacksonutil * * JSON characters with image conversion * * @version: $Revision $ $Date $ $ lastchangedby$ * */public Final class Jacksonutil {public static objectmapper objectmapper;/** * Use a generic method to convert a JSON string to the appropriate JAV The Abean object. * (1) Convert to normal javabean:readvalue (json,student.class) * (2) to list, such as List<student>, pass the second argument to Student * []. Class. Then use the Arrays.aslist () method to convert the resulting array to a specific type of list * * @param jsonstr * @param valueType * @return */public static <T> T ReadValue (String jsonstr, class<t> valueType) {if (Objectmapper = = null) {Objectmapper = new Objectmapper ();} try {return Objectmapper.readvalue (jsonstr, ValueType);} catch (Exception e) {e.printstacktrace ();} return null;} /** * JSON array goto list * @param jsonstr * @param valuetyperef * @return */public static <T> t ReadValue (String jsonstr, t Ypereference<t> valuetyperef) {if (ObjectmaPper = = null) {Objectmapper = new Objectmapper ();} try {return Objectmapper.readvalue (jsonstr, valuetyperef);} catch (Exception e) {e.printstacktrace ();} return null;} /** * Convert JavaBean to JSON String * * @param object * @return */public static string ToJSon (Object object) {if (Objectmapper = = N ull) {objectmapper = new Objectmapper ();} try {return objectmapper.writevalueasstring (object),} catch (Exception e) {e.printstacktrace ();} return null;}} </span>

3.jackson Data Conversion specific implementation

<span style= "FONT-SIZE:18PX;" >package Com.jackson.main;import Java.util.arraylist;import Java.util.list;import Com.fasterxml.jackson.core.type.typereference;import Com.jackson.bean.deptbean;import Com.jackson.bean.UserBean; Import com.jackson.utils.jacksonutil;/** * Instance implementation uses Jackson to convert entity objects to and from JSON strings * @author Liangming.deng * */public class Jacksondemo {public static void main (string[] args) {UserBean userBean1 = new UserBean (1, "Liubei", "123", "[Email pro Tected] "); UserBean userBean2 = new UserBean (2, "Guanyu", "123", "[email protected]"); UserBean userBean3 = new UserBean (3, "Zhangfei", "123", "[email protected]"); list<userbean> Userbeans = new arraylist<> (); Userbeans.add (userBean1); Userbeans.add (userBean2); Userbeans.add (USERBEAN3);D Eptbean Deptbean = new Deptbean (1, "Sanguo", Userbeans);//Object turn jsonstring Userbeantojson = Jacksonutil.tojson (USERBEAN1); String Deptbeantojson = Jacksonutil.tojson (Deptbean); System.out.println ("Deptbean to JSON:" + DEPTBEANTOJSOn); System.out.println ("UserBean to JSON:" + Userbeantojson),//json to string UserBean Jsontouserbean = Jacksonutil.readvalue ( Userbeantojson, Userbean.class);D Eptbean Jsontodeptbean = Jacksonutil.readvalue (Deptbeantojson, DeptBean.class); SYSTEM.OUT.PRINTLN ("JSON to Deptbean" + jsontodeptbean.tostring ()); SYSTEM.OUT.PRINTLN ("JSON to UserBean" + jsontouserbean.tostring ()),//list to JSON string, string Listtojson = Jacksonutil.tojson (Userbeans); System.out.println ("List to JSON:" + Listtojson);//array json to listlist<userbean> Jsontouserbeans = Jacksonutil.readvalue (Listtojson, New typereference<list<userbean>> () {}); String userbeanstring = ""; for (UserBean Userbean:jsontouserbeans) {userbeanstring + = userbean.tostring () + "\ n";} SYSTEM.OUT.PRINTLN ("JSON to Userbeans:" + userbeanstring);}} </span>

Output Result:

<span style= "FONT-SIZE:18PX;" >deptbean to json:{"DeptID": 1, "Deptname": "Sanguo", "userbeanlist": [{"UserId": 1, "UserName": "Liubei", "Password": "123", "Email": "[email protected]"},{"userId": 2, "UserName": "Guanyu", "Password": "123", "email": "[email  Protected] "},{" UserId ": 3," UserName ":" Zhangfei "," Password ":" 123 "," Email ":" [email protected] "}]}userbean to json:{"UserId": 1, "UserName": "Liubei", "Password": "123", "Email": "[email protected]"}json to Deptbeandeptbean [ Deptid=1, Deptname=sanguo, Userbeanliststring=userbean [Userid=1, Username=liubei, password=123, [email  Protected]]userbean [userid=2, Username=guanyu, password=123, [Email protected]]userbean] [userId=3, UserName= Zhangfei, password=123, [Email protected]]]json to Userbeanuserbean [Userid=1, Username=liubei, password=123, [ Email protected]]list to Json:[{"userId": 1, "UserName": "Liubei", "Password": "123", "email": "[email  Protected] "},{" userId ": 2," UserName ":" Guanyu "," Password ":" 123 "," Email ":" [email protected] "},{" UserId ": 3," UserName ":" Zhangfei "," Password ":" 123 "," Email ":" [email protected] "}]json to Userbeans:userbean [Userid=1, Username=liubei, password=123, [Email protected]]userbean] [userId=2, UserName= Guanyu, password=123, [Email protected]]userbean [Userid=3, Username=zhangfei, password=123, [email  Protected]]</span>

third, the date of the entity object and JSON conversion

Jackson there are two ways to implement a date-dated entity object with JSON conversion

1). Defines the date object in the Entity object as String, and then converts the string to date when used, without modification.

2). When a Date object in an entity object is defined as a date type, it is necessary to integrate the conversion of jsonserializer<date> object completion dates, this paragraph will focus on

1. Add the date createdate in Userbean.java and Deptbean.java respectively

<span style= "FONT-SIZE:18PX;" >private Date createdate;        Public Date Getcreatedate () {return createdate;} public void Setcreatedate (Date createdate) {this.createdate = CreateDate;} </span>

2. Implement a tool class that integrates with Jsonserializer<date> objects

<span style= "FONT-SIZE:18PX;" >package com.jackson.utils;import java.io.ioexception;import Java.text.simpledateformat;import java.util.Date; Import Com.fasterxml.jackson.core.jsongenerator;import Com.fasterxml.jackson.core.jsonprocessingexception;import Com.fasterxml.jackson.databind.jsonserializer;import com.fasterxml.jackson.databind.serializerprovider;/** * Jackson Date Conversion Tool class * * @author Liangming.deng * */public class Jsondateformatfull extends jsonserializer<date> {/** * J Ackson supports date string format * "Yyyy-mm-dd ' T ' HH:mm:ss. Sssz "" Yyyy-mm-dd ' T ' HH:mm:ss. SSS ' Z ' "*" EEE, dd MMM yyyy HH:mm:ss zzz "" yyyy-mm-dd "*/@Overridepublic void serialize (Date value, Jsongenerator jgen,ser Ializerprovider provider) Throwsioexception, jsonprocessingexception {SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd ' T ' HH:mm:ss"); String formatteddate = Formatter.format (value); jgen.writestring (formatteddate);}} </span>

3. Add the following annotations to the date variable in Userbean.java and Deptbean.java

<span style= "FONT-SIZE:18PX;" > @JsonSerialize (using = jsondateformatefull.class) Private Date createdate;</span>

4.jackson Date Mutual transfer Concrete implementation

<span style= "FONT-SIZE:18PX;" >package com.jackson.main;import java.util.date;import Java.util.arraylist;import java.util.Calendar;import Java.util.list;import Com.fasterxml.jackson.core.type.typereference;import Com.jackson.bean.deptbean;import Com.jackson.bean.userbean;import com.jackson.utils.jacksonutil;/** * Using Jackson to achieve mutual transfer of JSON and entity objects * @author Liangming.deng * */public class Jacksondemo {public static void main (string[] args) {UserBean userBean1 = new UserBean (1, " Liubei "," 123 "," [email protected] "); Userbean1.setcreatedate (New Date (Calendar.getinstance (). Gettimeinmillis ())); UserBean userBean2 = new UserBean (2, "Guanyu", "123", "[email protected]"), Userbean2.setcreatedate (New Date ( Calendar.getinstance (). Gettimeinmillis ()); UserBean userBean3 = new UserBean (3, "Zhangfei", "123", "[email protected]"), Userbean3.setcreatedate (New Date ( Calendar.getinstance (). Gettimeinmillis ()); list<userbean> Userbeans = new arraylist<> (); Userbeans.add (userBean1); USERBEANS.ADD (userBean2); Userbeans.add (userBean3);D Eptbean Deptbean = new Deptbean (1, "Sanguo", Userbeans); Deptbean.setcreatedate (New Date (Calendar.getinstance (). Gettimeinmillis ()));//entity object to jsonstring Userbeantojson = Jacksonutil.tojson (USERBEAN1); String Deptbeantojson = Jacksonutil.tojson (Deptbean); System.out.println ("Deptbean to JSON:" + Deptbeantojson); System.out.println ("UserBean to JSON:" + Userbeantojson);//json turn entity object UserBean Jsontouserbean = Jacksonutil.readvalue ( Userbeantojson, Userbean.class);D Eptbean Jsontodeptbean = Jacksonutil.readvalue (Deptbeantojson, DeptBean.class); SYSTEM.OUT.PRINTLN ("JSON to Deptbean" + jsontodeptbean.tostring ()); SYSTEM.OUT.PRINTLN ("JSON to UserBean" + jsontouserbean.tostring ())//list turn jsonstring Listtojson = Jacksonutil.tojson ( Userbeans); System.out.println ("List to JSON:" + Listtojson);//json turn listlist<userbean> Jsontouserbeans = Jacksonutil.readvalue (Listtojson, New typereference<list<userbean>> () {}); String userbeanstring = ""; for (UserBeanUserbean:jsontouserbeans) {userbeanstring + = userbean.tostring () + "\ n";} SYSTEM.OUT.PRINTLN ("JSON to Userbeans:" + userbeanstring);}} </span>

5. Result output

<span style= "FONT-SIZE:18PX;" >deptbean to json:{"DeptID": 1, "Deptname": "Sanguo", "CreateDate": "2014-11-20t10:58:08", "userbeanlist": [{"UserId ": 1," UserName ":" Liubei "," Password ":" 123 "," Email ":" [email protected] "," CreateDate ":" 2014-11-20t10:58:08 "}, {"UserId": 2, "UserName": "Guanyu", "Password": "123", "Email": "[email protected]", "CreateDate": "2014-11-20t10 : 58:08 "},{" UserId ": 3," UserName ":" Zhangfei "," Password ":" 123 "," Email ":" [email protected] "," CreateDate ":" 2014-11-20t10:58:08 "}]}userbean to json:{" userId ": 1," UserName ":" Liubei "," Password ":" 123 "," email ":" [email  Protected] "," CreateDate ":" 2014-11-20t10:58:08 "}json to Deptbeandeptbean [Deptid=1, Deptname=sanguo, Userbeanliststring=userbean [Userid=1, Username=liubei, password=123, [email protected], CreateDate=Thu Nov 20 18:58:08 CST 2014]userbean [userid=2, Username=guanyu, password=123, [email protected], CreateDate=Thu Nov 20 18:58 : 2014]userbean CST [userid=3, Username=zhangfei, password=123, [Email protecTed], Createdate=thu Nov 18:58:08 CST 2014]]json to Userbeanuserbean [Userid=1, Username=liubei, password=123, [EMAIL&N Bsp;protected], Createdate=thu Nov 18:58:08 CST 2014]list to json:[{"userId": 1, "UserName": "Liubei", "Password": "123" , "email": "[email protected]", "CreateDate": "2014-11-20t10:58:08"},{"UserId": 2, "UserName": "Guanyu", " Password ":" 123 "," Email ":" [email protected] "," CreateDate ":" 2014-11-20t10:58:08 "},{" UserId ": 3," UserName ":" Zhangfei "," Password ":" 123 "," Email ":" [email protected] "," CreateDate ":" 2014-11-20t10:58:08 "}]json to Userbeans:userbean [Userid=1, Username=liubei, password=123, [email protected], Createdate=thu Nov 18:58:08 CST 2014]userbean [userid=2, Username=guanyu, password=123, [email protected], Createdate=thu Nov 18:58:08 CST 2014] UserBean [Userid=3, Username=zhangfei, password=123, [email protected], Createdate=thu Nov 18:58:08 CST 2014] </span>

The above is all content of this blog post.

Source: http://download.csdn.net/detail/a123demi/8394327


Jackson implements cross-transfer of object objects to JSON strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.