gpt4 book ai didi

java - jackson 混音 : How to Ignore or Rename fields from class as tree

转载 作者:行者123 更新时间:2023-11-30 05:51:21 26 4
gpt4 key购买 nike

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

使用 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);
}
}

最佳答案

这应该会给你你正在寻找的输出。更改您的 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,这样你就得到了一个扁平的结构。

关于java - jackson 混音 : How to Ignore or Rename fields from class as tree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com