Jackson mixin:如何将类中的字段忽略或重命名为树

时间:2018-12-20 16:18:21

标签: java jackson mixins objectmapper

我正在尝试对表示为树的类进行深度过滤(重命名/忽略字段)。

借助Jackson Mixin,我可以重命名或忽略根级别的字段。我要实现的是如何在多个级别上进行过滤(重命名/忽略)?

例如,我有一棵有两个类的树。 A类是根,B是树中第二级深度。通过应用Jackson Mxiin,我想从根A过滤属性a2,从根B过滤属性b1。

代表根类的A类

public class A {
  private String a1;
  private String a2;
  private B b;

  public A(String a1, String a2, B b) {
      this.a1 = a1;
      this.a2 = a2;
      this.b = b;
  }

  public String getA1() {
      return a1;
  }

  public void setA1(String a1) {
      this.a1 = a1;
  }

  public String getA2() {
      return a2;
  }

  public void setA2(String a2) {
      this.a2 = a2;
  }

  public B getB() {
      return b;
  }

  public void setB(B b) {
      this.b = b;
  }

}

B级-二级深度

public class B {

      private String b1;
      private String b2;

      public B(String b2, String b1) {
          this.b1 = b1;
          this.b2 = b2;
      }

      public String getB1() {
          return b1;
      }

      public void setB1(String b1) {
          this.b1 = b1;
      }

      public String getB2() {
          return b2;
      }

      public void setB2(String b2) {
          this.b2 = b2;
      }
    }

过滤器

public interface AMixIn {
  // Filter for A (implemented to filter second depth as well)
  @JsonIgnore
  String getA2();

  @JsonIgnore
  public BMixIn getB();
}

public interface BMixIn {
  // Filter for B
  @JsonIgnore
  public String getB1();

}

测试

public class SecondLevelTest {
  // Test
  private ObjectMapper mapper = null;
  private ObjectWriter writer = null;

  @Before
  public void setUp() {
      // init
      mapper = new ObjectMapper();
      mapper.setMixIns(ImmutableMap.<Class<?>, Class<?>>of(A.class, AMixIn.class));
      writer = mapper.writer().with(SerializationFeature.INDENT_OUTPUT);
  }

  @Test
  public void rename_field_jackson() throws JsonProcessingException {

      B b = new B("vb1", "vb2");
      A a = new A("va1", "va2", b);

      // I want to get this result
      // {
      // "a1" : "va1",
      // "b2" : "vb2"
      // }
      String json = writer.writeValueAsString(a);
      System.out.println(json);
  }
}

1 个答案:

答案 0 :(得分:1)

这应该为您提供所需的输出。将您的setUp()更改为也使用BMixIn

@Before
public void setUp() {
    // init
    mapper = new ObjectMapper();
    mapper.setMixIns(ImmutableMap.of(A.class, AMixIn.class, B.class, BMixIn.class));
    writer = mapper.writer().with(SerializationFeature.INDENT_OUTPUT);
}

然后更改AMixIn以解开B

public interface AMixIn {
    // Filter for A (implemented to filter second depth as well)
    @JsonIgnore
    String getA2();

    @JsonUnwrapped
    public BMixIn getB();
}

忘记注册BMixIn导致其@JsonIgnore从未使用过。 @JsonUnwrapped取消嵌套b,这样您就可以获得一个扁平的结构。