zoukankan      html  css  js  c++  java
  • fasterxml Jackson 各种使用场景以及序列化、反序列化的时候忽略不必要的Properties

    1. 将json字符串转成Map:

    public static Map jsonToMap(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
            LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
        }
        return null;
    }
    
    2. 将json字符串转换成java对象:
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return (T) objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
        }
        return null;
    }

    3. 将Java对象转换成Josn:

    public static String objectToJsonString(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
        }
        return null;
    }

    4. 序列化、反序列化时忽略不必要的属性:

    序列化时可以在成员变量上面加入@JsonIgnore注解:

        @JsonInclude(content = Include.NON_NULL, value = Include.NON_NULL)
        private String test;

        @JsonInclude(content = Include.NON_EMPTY, value = Include.NON_EMPTY)
        private List<Available> vehicle = new ArrayList<Available>();

    反序列化时可以直接在类上面加入@JsonIgnoreProperties,忽略所有未知属性,也可以单个去忽略

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class TestObject {...}
  • 相关阅读:
    为公司转型做的一些准备——数据库设计技术
    jdbc多种实现方式
    JNuit
    JDBC初体验
    jsp原理
    jsp登陆
    jsp homework(*)
    集合(5)
    集合(4)
    集合(3)
  • 原文地址:https://www.cnblogs.com/cnsec/p/13407167.html
Copyright © 2011-2022 走看看