Json工具类 ---JsonUtil

import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static <T> String entity2Json(T t) {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    public static <T> T json2Entity(String json, Class<T> clazz) {
        T t = null;
        try {
            t = objectMapper.readValue(json, clazz);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    @SuppressWarnings("unchecked")
    public static <T> T json2Entity(String json, String reqName, boolean isReq) {
        T t = null;
        try {
            Class<T> clazz = (Class<T>) Class.forName(reqName);
            t = json2Entity(json, clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return t;
    }

    /** * 返回类型自定义,可返回数组 * * @param jsonVal * @param clazz * @return */
    public static <T> Object json2Object(String jsonVal, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonVal, clazz);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

你可能感兴趣的:(json)