Jackson 转换实体或Map为String问题

主要记载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}}“

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值