Jackson 序列化和反序列化忽略字段

转自:https://blog.csdn.net/yu870646595/article/details/78523402

一、设置Jackson序列化时只包含不为空的字段

new ObjectMapper().setSerializationInclusion(Include.NON_NULL);

二、设置在反序列化时忽略在JSON字符串中存在,而在Java中不存在的属性

new ObjectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

三、Jackson序列化时忽略字段的方式

1、方式一:FilterProvider

a)在需要忽略某些字段的bean上添加@JsonFilter("fieldFilter")

b)ObjectMapper设置过滤器

   FilterProvider filterProvider = new SimpleFilterProvider();

   SimpleBeanPropertyFilter fieldFilter = SimpleBeanPropertyFilter().serializeAllExcept("name");
   filterProvider.addFilter("fieldFilter");

   new ObjectMapper.setFilters(filterProvider );

2、方式二:使用@JsonIgnore

   在需要忽略的字段上标注注解@JsonIgnore,在序列化时即可忽略该字段

转自:https://blog.csdn.net/ngl272/article/details/70217104

用Jackson解决就非常容易了,只需要在实体类上加上注解就可以。

@JsonIgnoreProperties(ignoreUnknown = true)
class ExtraBean {
    private boolean is_museuser;
 
    public boolean isIs_museuser() {
        return is_museuser;
    }
 
    public void setIs_museuser(boolean is_museuser) {
        this.is_museuser = is_museuser;
    }
}

@JsonIgnore注解用来忽略某些字段,可以用在Field或者Getter方法上,用在Setter方法时,和Filed效果一样。这个注解只能用在POJO存在的字段要忽略的情况,不能满足现在需要的情况。

@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段,可以满足当前的需要。这个注解还可以指定要忽略的字段。使用方法如下:

@JsonIgnoreProperties({ "internalId", "secretKey" })
指定的字段不会被序列化和反序列化。

猜你喜欢

转载自blog.csdn.net/Dongguabai/article/details/89735187