Jackson Ignore Properties on Marshalling – Jackson忽略了关于装运的属性

最后修改: 2013年 12月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.

本教程将展示如何使用Jackson 2.x将一个对象序列化为JSON时忽略某些字段

This is very useful when the Jackson defaults aren’t enough and we need to control exactly what gets serialized to JSON — and there are several ways to ignore properties.

当Jackson的默认值不够用,我们需要准确控制哪些东西被序列化为JSON时,这是非常有用的–而且有几种方法可以忽略属性。

To dig deeper and learn other cool things we can do with Jackson, head on over to the main Jackson tutorial.

要想深入挖掘并了解我们可以用杰克逊做的其他很酷的事情,请前往杰克逊主要教程

2. Ignore Fields at the Class Level

2.在类一级忽略字段

We can ignore specific fields at the class level, using the @JsonIgnoreProperties annotation and specifying the fields by name:

我们可以在类的层面上忽略特定的字段,使用@JsonIgnoreProperties注解并通过名称指定字段

@JsonIgnoreProperties(value = { "intValue" })
public class MyDto {

    private String stringValue;
    private int intValue;
    private boolean booleanValue;

    public MyDto() {
        super();
    }

    // standard setters and getters are not shown
}

We can now test that, after the object is written to JSON, the field is indeed not part of the output:

我们现在可以测试,在对象被写入JSON后,该字段确实不是输出的一部分。

@Test
public void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
}

3. Ignore Field at the Field Level

3.在田间地头忽略田野

We can also ignore a field directly via the @JsonIgnore annotation directly on the field:

我们也可以通过@JsonIgnore注解直接忽略一个字段

public class MyDto {

    private String stringValue;
    @JsonIgnore
    private int intValue;
    private boolean booleanValue;

    public MyDto() {
        super();
    }

    // standard setters and getters are not shown
}

We can now test that the intValue field is indeed not part of the serialized JSON output:

我们现在可以测试intValue字段确实不是序列化JSON输出的一部分。

@Test
public void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect() 
  throws JsonParseException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
}

4. Ignore All Fields by Type

4.按类型忽略所有字段

Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly:

最后,我们可以使用@JsonIgnoreType注解,忽略指定类型的所有字段。如果我们控制了类型,那么我们可以直接注解类。

@JsonIgnoreType
public class SomeType { ... }

More often than not, however, we don’t have control of the class itself. In this case, we can make good use of Jackson mixins.

然而,更多的时候,我们并不能控制类本身。在这种情况下,我们可以很好地利用Jackson mixins.

First, we define a MixIn for the type we’d like to ignore and annotate that with @JsonIgnoreType instead:

首先,我们为我们想要忽略的类型定义一个MixIn,然后用@JsonIgnoreType来注释它。

@JsonIgnoreType
public class MyMixInForIgnoreType {}

Then we register that mixin to replace (and ignore) all String[] types during marshalling:

然后我们注册该混合器,以便在编排过程中替换(并忽略)所有String[]类型。

mapper.addMixInAnnotations(String[].class, MyMixInForIgnoreType.class);

At this point, all String arrays will be ignored instead of marshalled to JSON:

在这一点上,所有的String数组将被忽略,而不是被marshalled为JSON。

@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect()
  throws JsonParseException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
    MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
    dtoObject.setBooleanValue(true);

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}

And here is our DTO:

而这里是我们的DTO。

public class MyDtoWithSpecialField {
    private String[] stringValue;
    private int intValue;
    private boolean booleanValue;
}

Note: Since version 2.5, it seems that we can’t use this method to ignore primitive data types, but we can use it for custom data types and arrays.

注意:从2.5版本开始,我们似乎不能用这个方法来忽略原始数据类型,但我们可以对自定义数据类型和数组使用。

5. Ignore Fields Using Filters

5.使用过滤器忽略字段

Finally, we can also use filters to ignore specific fields in Jackson.

最后,我们还可以使用过滤器来忽略杰克逊中的特定字段

First, we need to define the filter on the Java object:

首先,我们需要在Java对象上定义过滤器。

@JsonFilter("myFilter")
public class MyDtoWithFilter { ... }

Then we define a simple filter that will ignore the intValue field:

然后我们定义一个简单的过滤器,它将忽略intValue字段。

SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
  .serializeAllExcept("intValue");
FilterProvider filters = new SimpleFilterProvider()
  .addFilter("myFilter", theFilter);

Now we can serialize the object and make sure that the intValue field is not present in the JSON output:

现在我们可以将对象序列化,并确保intValue字段不存在于JSON输出中。

@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() 
  throws JsonParseException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
      .serializeAllExcept("intValue");
    FilterProvider filters = new SimpleFilterProvider()
      .addFilter("myFilter", theFilter);

    MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}

6. Conclusion

6.结论

This article illustrated how to ignore fields on serialization. We did this first by name and then directly, and finally, we ignored the entire java type with MixIns and used filters for more control of the output.

这篇文章说明了如何在序列化时忽略字段。我们首先通过名字来做,然后直接做,最后,我们用MixIns忽略了整个java类型,并使用过滤器对输出进行更多的控制。

The implementation of all these examples and code snippets can be found in the GitHub project.

所有这些例子和代码片段的实现都可以在GitHub项目中找到。