Jackson實現Object對象與Json字符串的互轉

在項目開發過程當中,當客戶端與服務器響應時,數據交互是必不可少的。然而經過Json實現數據交互成爲咱們開發中的一部分,進而Jackson爲咱們的Json轉化提供了很好的機制。下面我將利用實例總結如何使用jackson.java

1、準備json

若是你須要使用jackson,你必須得導入相應的架包,有以下三個包數組

jackson-annotations;jackson-core;jackson-databind服務器

Maven引入依賴代碼app

 

<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>

 

 

2、不帶日期的對象實體與json互轉ide

 

1.定義實體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;
	}
	
	
	
	@Override
	public String toString() {
		String userBeanListString = "";
		for (UserBean userBean : userBeanList) {
			userBeanListString += 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;
	}
	@Override
	public String toString() {
		return "UserBean [userId=" + userId + ", userName=" + userName
				+ ", password=" + password + ", 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>

注意:在實體中必須存在無參的構造方法,不然轉換時會有以下異常;工具

 

 

<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數據轉換工具類

 

 

<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字符與對像轉換
 * 
 * @version: $Revision$ $Date$ $LastChangedBy$
 *
 */
public final class JacksonUtil {

	public static ObjectMapper objectMapper;

	/**
	 * 使用泛型方法,把json字符串轉換爲相應的JavaBean對象。
	 * (1)轉換爲普通JavaBean:readValue(json,Student.class)
	 * (2)轉換爲List,如List<Student>,將第二個參數傳遞爲Student
	 * [].class.而後使用Arrays.asList();方法把獲得的數組轉換爲特定類型的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數組轉List
	 * @param jsonStr
	 * @param valueTypeRef
	 * @return
	 */
	public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}

		try {
			return objectMapper.readValue(jsonStr, valueTypeRef);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 把JavaBean轉換爲json字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJSon(Object object) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}

		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}</span>

 

 

3.jackson數據轉換具體實現

 

<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;

/**
 * 實例實現利用jackson實現實體對象與json字符串的互相轉換
 * @author liangming.deng
 *
 */
public class JacksonDemo {
	public static void main(String[] args){
		
		UserBean userBean1 = new UserBean(1, "liubei", "123", "liubei@163.com");
		UserBean userBean2 = new UserBean(2, "guanyu", "123", "guanyu@163.com");
		UserBean userBean3 = new UserBean(3, "zhangfei", "123", "zhangfei@163.com");
		
		
		List<UserBean> userBeans = new ArrayList<>();
		userBeans.add(userBean1);
		userBeans.add(userBean2);
		userBeans.add(userBean3);
		
		DeptBean deptBean = new DeptBean(1, "sanguo", userBeans);
		//對象轉json
		String userBeanToJson = JacksonUtil.toJSon(userBean1);
		String deptBeanToJson = JacksonUtil.toJSon(deptBean);
		
		System.out.println("deptBean to json:" + deptBeanToJson);
		System.out.println("userBean to json:" + userBeanToJson);
		
		//json轉字符串
		UserBean jsonToUserBean = JacksonUtil.readValue(userBeanToJson, UserBean.class);
		DeptBean jsonToDeptBean = JacksonUtil.readValue(deptBeanToJson, DeptBean.class);
		
		System.out.println("json to DeptBean" + jsonToDeptBean.toString());
		System.out.println("json to UserBean" + jsonToUserBean.toString());
		
		//List 轉json字符串
		String listToJson = JacksonUtil.toJSon(userBeans);
		System.out.println("list to json:" + listToJson);
		
		//數組json轉 List
		List<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>


輸出結果:ui

 

 

<span style="font-size:18px;">deptBean to json:{"deptId":1,"deptName":"sanguo","userBeanList":[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com"}]}
userBean to json:{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"}
json to DeptBeanDeptBean [deptId=1, deptName=sanguo, 
userBeanListString=UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com]
]
json to UserBeanUserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
list to json:[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com"}]
json to userBeans:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com]
</span>

 

 

3、帶日期的實體對象與json轉換this

 

jackson實現帶日期的實體對象與json轉換有兩種方法spa

1).將實體對象中的日期對象定義爲String型,在使用的時候再將String型轉換爲Date型使用,其餘就無需修改。

2).當實體對象中的日期對象定義爲Date型,就須要經過集成JsonSerializer<Date>對象完成日期的轉換,本段將重點講解

1.在UserBean.java和DeptBean.java中分別添加Date createDate

 

<span style="font-size:18px;">	private Date createDate;	
        public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}</span>

 

 

2.實現集成於JsonSerializer<Date>對象的工具類

 

 

<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日期轉換工具類
 * 
 * @author liangming.deng
 *
 */
public class JsonDateFormatFull extends JsonSerializer<Date> {

	/**
	 * Jackson支持日期字符串格式
	 * "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"
	 */
	@Override
	public void serialize(Date value, JsonGenerator jgen,
			SerializerProvider provider) throws

	IOException, JsonProcessingException {
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ss");
		String formattedDate = formatter.format(value);
		jgen.writeString(formattedDate);

	}

}
</span>

 

 

3.在UserBean.java和DeptBean.java中Date變量加入以下註解

 

<span style="font-size:18px;">	@JsonSerialize(using = JsonDateFormateFull.class)
	private Date createDate;</span>

 

 

4.jackson日期互轉具體實現

 

 

<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;

/**
 *利用jackson實現Json與實體對象的互轉
 * @author liangming.deng
 *
 */
public class JacksonDemo {
	public static void main(String[] args){
		
		UserBean userBean1 = new UserBean(1, "liubei", "123", "liubei@163.com");
		userBean1.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
		UserBean userBean2 = new UserBean(2, "guanyu", "123", "guanyu@163.com");
		userBean2.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
		UserBean userBean3 = new UserBean(3, "zhangfei", "123", "zhangfei@163.com");
		userBean3.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
		
		
		List<UserBean> userBeans = new ArrayList<>();
		userBeans.add(userBean1);
		userBeans.add(userBean2);
		userBeans.add(userBean3);
		
		DeptBean deptBean = new DeptBean(1, "sanguo", userBeans);
		deptBean.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
		//實體對象 轉json
		String userBeanToJson = JacksonUtil.toJSon(userBean1);
		String deptBeanToJson = JacksonUtil.toJSon(deptBean);
		
		System.out.println("deptBean to json:" + deptBeanToJson);
		System.out.println("userBean to json:" + userBeanToJson);
		
		//json 轉實體對象
		UserBean jsonToUserBean = JacksonUtil.readValue(userBeanToJson, UserBean.class);
		DeptBean jsonToDeptBean = JacksonUtil.readValue(deptBeanToJson, DeptBean.class);
		
		System.out.println("json to DeptBean" + jsonToDeptBean.toString());
		System.out.println("json to UserBean" + jsonToUserBean.toString());
		
		//List 轉json
		String listToJson = JacksonUtil.toJSon(userBeans);
		System.out.println("list to json:" + listToJson);
		
		//json 轉 List
		List<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>

 

 

5.結果輸出

 

 

<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":"liubei@163.com","createDate":"2014-11-20T10:58:08"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com","createDate":"2014-11-20T10:58:08"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com","createDate":"2014-11-20T10:58:08"}]}
userBean to json:{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com","createDate":"2014-11-20T10:58:08"}
json to DeptBeanDeptBean [deptId=1, deptName=sanguo, 
userBeanListString=UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
]
json to UserBeanUserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
list to json:[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com","createDate":"2014-11-20T10:58:08"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com","createDate":"2014-11-20T10:58:08"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com","createDate":"2014-11-20T10:58:08"}]
json to userBeans:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com, createDate=Thu Nov 20 18:58:08 CST 2014]
</span>


以上爲本博文的全部內容。

 

源碼下載地址:http://download.csdn.net/detail/a123demi/8394327

相關文章
相關標籤/搜索