json串操作

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;

/**
 * Json序列化与反序列化工具类
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转JSON
     *
     * @param t
     *            对象
     * @return
     */
    public static <T> String toJson(T t){
        try {
            return objectMapper.writeValueAsString(t);
        }catch (IOException e){
            throw new RuntimeException("JsonUtil.toJson error",e);
        }
    }

    /**
     * JSON转对象
     *
     * @param jsonString
     *            json字符串
     * @param valueType
     *            对象类型
     * @return
     */
    public static <T> T fromJson(String jsonString, Class<T> valueType) {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, valueType);
        } catch (IOException e) {
            throw new RuntimeException("JsonUtil.fromJson error", e);
        }

    }

    /**
     *
     * @param jsonString
     *            json字符串
     * @param typeReference
     *            泛型信息
     * @return
     */
    public static <T> T fromJson(String jsonString, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, typeReference);
        } catch (IOException e) {
            throw new RuntimeException("JsonUtil.fromJson error", e);
        }
    }


    /**
     * 判断是否json 字符串
     * @param str
     * @return
     */
    public static boolean isJsonString(String str) {
        if(StringUtils.isBlank(str)){
            return false;
        }
        try {
            objectMapper.readTree(str);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

 

posted @ 2019-06-22 12:05  cc-robot  阅读(243)  评论(0编辑  收藏  举报