如何告诉Jackson跳过未包装的子POJO字段,以便当我解析到CSV时,它会跳过整个列?
这是一个完整的代码示例:
public class FooTest {
class Foo {
String something = "value";
@JsonUnwrapped(prefix = "bar.")
@JsonIgnoreProperties({ "toBeIgnored" })
Bar bar;
public String getSomething() {
return something;
}
public Bar getBar() {
return bar;
}
}
class Bar {
String toBeIgnored;
public String getToBeIgnored() {
return toBeIgnored;
}
}
@Test
public void fooTest() throws IOException {
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(Foo.class).withHeader();
ObjectWriter csvWriter = mapper.writer(schema);
OutputStream outputStream = new ByteArrayOutputStream();
SequenceWriter writer = csvWriter.writeValues(outputStream);
Foo foo = new Foo();
foo.bar = new Bar();
String toBeIgnored = "should not be parsed";
foo.bar.toBeIgnored = toBeIgnored;
writer.write(foo);
String result = outputStream.toString();
assertThat(result).doesNotContain(toBeIgnored);
assertThat(result).contains("something");
assertThat(result).doesNotContain("bar.toBeIgnored");
}
}
注意,我不能以任何方式修改类< code>Bar。
如何在类Foo
中指定要忽略bar.toBeIgnored
?
< code > JsonIgnoreProperties 对于跳过该值很有用,但对于跳过整列并不有用。当前代码将输出一个列< code>bar.toBeIgnored为空值的CSV。我只想跳过这个专栏。
使用:< code > @ JsonIgnoreProperties({ " toBeIgnoredA "," toBeIgnoredB" })
public class ToSerialize {
@JsonUnwrapped(prefix = "toBeUnwrapped")
@JsonIgnoreProperties({ "toBeIgnoredA", "toBeIgnoredB" })
public ToBeUnwrapped toBeUnwrapped;
}
或者(很长一段时间)为< code > tobe unwrapper 创建包装类,在这里您可以自由地配置JSON注释,而不接触实际的< code > tobe unwrapper 类