Jackson 转换实体或Map为String问题

来源:互联网 发布:ug加工编程 编辑:程序博客网 时间:2024/05/16 07:35

主要记载Object或者Map转换为String时,去除NULL值,引用jar包为:

        <dependency>            <groupId>com.fasterxml.jackson</groupId>            <artifactId>jackson-parent</artifactId>            <version>2.6.2</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-annotations</artifactId>            <version>2.6.0</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>2.6.4</version>        </dependency>

1. 转换Map为String问题

        ObjectMapper mapper = new ObjectMapper();        //设置不写NULLmap值        mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);        Map testMap = new HashMap();        testMap.put("a", null);        testMap.put("b", 11);        String outJson = null;        try {            outJson = mapper.writeValueAsString(testMap);        } catch (JsonProcessingException e) {            e.printStackTrace();        }        System.out.println(outJson);
              输出结果为: {"b":11}

2. 转换Object 为String问题

标记类型解释说明:

       Include.Include.ALWAYS 默认        Include.NON_DEFAULT 属性为默认值不序列化        Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化        Include.NON_NULL 属性为NULL 不序列化 

方法一:对ObjectMapper进行属性设置

ObjectMapper mapper = new ObjectMapper();        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);        Map testMap = new HashMap();        testMap.put("a", null);        testMap.put("b", 11);        User user = new User(1, null, null, testMap);        String outJson = null;        try {            outJson = mapper.writeValueAsString(user);        } catch (JsonProcessingException e) {            e.printStackTrace();        }        System.out.println(outJson);
              输出结果为: “{"id":1,"a":{"a":null,"b":11}}“, 如果添加设置Map转换为String的属性,则输出结果为:“{"id":1,"a":{"b":11}}”

方法二:通过设置注解实现,方法上添加则只对具体属性有效,类上添加对所有属性有效

@JsonInclude(JsonInclude.Include.NON_NULL)public class User {    public User() {    }
           Object必须为VO形式,输出结果为: “{"id":1,"a":{"a":null,"b":11}}“

0 0