jackson 用法总结

1.序列化与反序列化封装

 

 private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);


    /**
     * Object对象转换为String
     *
     * @param data Object对象
     * @return Object对象对应的字符串
     */
    public static <T> String toJsonString(T data) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.writeValueAsString(data);
        } catch (JsonProcessingException ex) {
            if (logger.isErrorEnabled()) {
                logger.error("json parse error:", ex);
            }
            return "json parse error:" + ex.getMessage();
        }
    }

    /**
     * 字符串转换为对象
     *
     * @param json  字符串
     * @param clazz 类类型
     * @return clazz类型的对象
     */
    public static <R> R json2Object(String json, Class<R> clazz) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.readValue(json, clazz);
        } catch (Exception ex) {
            if (logger.isErrorEnabled()) {
                logger.error("json parse error:", ex);
            }
        }
        return null;
    }

    /**
     * 字节转换为对象
     *
     * @param jsonBuffer 字节
     * @param clazz      类类型
     * @return clazz类型的对象
     */
    public static <R> R json2Object(byte[] jsonBuffer, Class<R> clazz) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.readValue(jsonBuffer, clazz);
        } catch (Exception ex) {
            if (logger.isErrorEnabled()) {
                logger.error("json parse error:", ex);
            }
        }
        return null;

    }

    /**
     * 字符串转换为对象数组
     *
     * @param json  字符串
     * @param clazz 类类型
     * @return clazz类型的对象数组
     */
    public static <T> List<T> json2List(String json, Class<T> clazz) {
        List<T> list = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            TypeReference<List<T>> typeRef = new TypeReference<List<T>>() {
                @Override
                public Type getType() {
                    return new ParameterizedType() {
                        @Override
                        public Type[] getActualTypeArguments() {
                            return new Type[]{clazz};
                        }
                        @Override
                        public Type getRawType() {
                            return List.class;
                        }
                        @Override
                        public Type getOwnerType() {
                            return null;
                        }
                    };
                }
            };
            list = mapper.readValue(json, typeRef);
        } catch (Exception ex) {
            if (logger.isErrorEnabled()) {
                logger.error("json parse error:", ex);
            }
        }
        return list;
    }

2.自定义jackson

https://blog.csdn.net/weixin_35772453/article/details/69666225

posted @ 2018-03-26 15:43  Gyoung  阅读(1294)  评论(0编辑  收藏  举报