工具类json处理

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

 

你可能感兴趣的:(java)