ツールクラスjson処理

2251 ワード

package com.jzlife.servantequity.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

/**
 * class util to process json data.
 */
public class JsonUtil {

	public static final ObjectMapper om = new ObjectMapper();
	public static final Gson gson = new Gson();

	@SuppressWarnings("unchecked")
	public static  T getEntity(Object data, Class clazz) {
		if (data.getClass() == clazz) {
			return (T) data;
		}
		try {
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			String json = om.writeValueAsString(data);
			return om.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getJson(Object data) {
		try {
			return om.writeValueAsString(data);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static  T getEntity(String json, Class clazz) {
		try {
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			return om.readValue(json, clazz);
		} catch (Exception e) {
			return null;
		}
	}

	public static  T getEntity(String json, JavaType javatype) {
		try {
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			return om.readValue(json, javatype);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String GsonString(Object object) {
		if (object != null) {
			return gson.toJson(object);
		}
		return null;
	}

	/**
	 *  json     cls   
	 * 
	 * @param gsonString
	 * @param cls
	 * @return
	 */
	public static  T GsonToBean(String gsonString, Class cls) {
		T t = null;
		if (gson != null) {
			//   json       , json    
			t = gson.fromJson(gsonString, cls);
		}
		return t;
	}

	/**
	 *       
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static  T getEntityFsj(String json, TypeReference t) {
		try {
			return JSON.parseObject(json, t);
		} catch (Exception e) {
			return null;
		}
	}
}