美文网首页
Jackson全面解析--注解全讲解八(@JsonIgnore,

Jackson全面解析--注解全讲解八(@JsonIgnore,

作者: 牧羊人刘俏 | 来源:发表于2020-12-07 17:20 被阅读0次

@JsonIgnore

一般在序列化或是反序列化的时候,有些字段你不希望暴露出去,可以使用@JsonIgnore注解打在属性上面,这样这个字段在序列化和反序列化的时候就会被忽略掉
示例代码如下

 @Getter
    @Setter
    @NoArgsConstructor
    @JsonIdentityInfo(property = "name",generator = ObjectIdGenerators.PropertyGenerator.class)
    class Boss{

        String name;
        @JsonIgnore
        String department;
        //@JsonManagedReference
        List<Employee> employees;


    }
测试代码如下
 @Test
    public void JsonIgnoreTest() throws Exception{

        CombineJacksonAnnotation.Boss boss = new CombineJacksonAnnotation.Boss();
        boss.setName("boss");
        boss.setDepartment("cto");
        System.out.println(om.writeValueAsString(boss));


    }
结果如下
{
  "name" : "boss",
  "employees" : null
}

可以看到department字段被成功的ignore掉了。

@JsonIgnoreProperties

如果你觉得在每个属性上面打标签比较复杂,可以在class上面使用@JsonIgnoreProperties一次性将所有需要忽略的字段都写上就可以了。
如下


    @Getter
    @Setter
    @NoArgsConstructor
    @JsonIdentityInfo(property = "name",generator = ObjectIdGenerators.PropertyGenerator.class)
    @JsonIgnoreProperties(value = "name")
    class Boss{

        String name;
        String department;
        //@JsonManagedReference
        List<Employee> employees;
}

@JsonIgnoreType

如果一个class的属性是也是个pojo,你需要全部的ignore掉,那么在这个pojo上面打上@JsonIgnoreType标签就可以了。

相关文章

网友评论

      本文标题:Jackson全面解析--注解全讲解八(@JsonIgnore,

      本文链接:https://www.haomeiwen.com/subject/castgktx.html