java jackson json字符串、对象、json结构之间互相转换

public class JSONUtil {

    /**
     * json转对象
     *
     * @param json
     * @param clazz<T>
     * @return
     */
    public final static <T> T parseObject(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            //忽略未知属性的反序列化
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json转node
     *
     * @param json
     * @return
     */
    public final static <T> T toNode(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return (T) mapper.readTree(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对象转json
     *
     * @param obj
     * @return
     */
    public final static String toJSONString(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*/**
     * 对象转jsonNode
     * @param Object
     * @return jsonNode
     */
    public final static <T> T objToJsonNode(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String s = mapper.writeValueAsString(obj);
            return (T) mapper.readTree(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换
     *
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public final static <T> T convertValue(Object obj, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(obj, clazz);
    }
}

posted @ 2022-07-14 16:20  lambertlt  阅读(601)  评论(0编辑  收藏  举报