1. 程式人生 > >json轉換工具類

json轉換工具類

package com.test.common;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
/**
 * maven引入:
 *jackson-mapper-asl
 *jackson-core-asl
 *fastjson 
 */
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * json主鍵轉換工具類
 * @author 
 *
 */
public class JSONUtils{
	private static ObjectMapper mapper = new ObjectMapper();
	private static Logger log = Logger.getLogger(JSONUtils.class);
	private static final String PAGE_TOTAL = "total";
	private static final String PAGE_ROWS = "rows";
	
	/**
	 * 將json資料轉成指定型別的物件
	 * @param content
	 * @param valueType
	 * @return
	 */
	public static <T>T convertJson2Object(String content, Class<T> valueType){
		if(content == null || content.equals("")) return null;
		 
		return JSON.parseObject(content, valueType);
	}

	/**
	 * 將Object物件轉成指定型別的物件
	 * @param object
	 * @param objectType
	 * @return
	 */
	public static <T>T converEntityToObject(Object object,Class<T> objectType){
		try {
			return object == null ? null : JSON.parseObject(JSON.toJSONString(object),objectType);
		} catch (Exception e) {
			log.error("json解析錯誤:"+e.getMessage());
		}
		return null;
	}

	/**
	 * 將物件格式化成json格式資料
	 * @param obj
	 * @return
	 */
	public static String convertObject2Json(Object obj) {
		return JSON.toJSONString(obj, true);
	}
	
	/**
	 * 將json格式資料轉成Map物件
	 * @param content
	 * @return
	 */
	public static Map<String, Object> convertJson2Map(String content){
		try {
			return mapper.readValue(content,  new TypeReference<Map<String,Object>>() { });
		} catch (IOException e) {
			log.error("json解析錯誤:"+e.getMessage());
		}
		return null;
	}

	/**
	 * 將Object格式資料轉成JSONObject物件
	 * @param object
	 * @return
	 */
	public static JSONObject converEntityToJSONObject(Object object){
		try {
			return object == null ? new JSONObject() : JSONObject.parseObject(JSON.toJSONString(object));
		} catch (Exception e) {
			log.error("json解析錯誤:"+e.getMessage());
		}
		return null;
	}

	/**
	 * 將後臺傳過來的資料封裝返回前臺
	 * @param total			總條數
	 * @param resultList	分頁資料集
	 * @return
	 */
	public static Map<String, Object> resultMap(Long total,Collection<?> resultList){
		Map<String, Object> map = new  HashMap<String, Object>();
		map.put(PAGE_TOTAL, total);
		map.put(PAGE_ROWS,  resultList);
		return map;
	}
}