如何告诉 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");
}
}
请注意,我无法以任何方式修改 Bar
类。
如何在类 Foo
中指定我想要忽略 bar.toBeIgnored
?
JsonIgnoreProperties
对于跳过值而不是整个列很有用。当前代码将输出一个 CSV,其中 bar.toBeIgnored
列的值为空。我只是想跳过本专栏。
最佳答案
使用:@JsonIgnoreProperties({ "toBeIgnoredA", "toBeIgnoredB"})
public class ToSerialize {
@JsonUnwrapped(prefix = "toBeUnwrapped")
@JsonIgnoreProperties({ "toBeIgnoredA", "toBeIgnoredB" })
public ToBeUnwrapped toBeUnwrapped;
}
或者(很长的路要走)为 ToBeUnwrapped
创建包装类,您可以在其中自由配置 JSON 注释,而无需实际的 ToBeUnwrapped
类接触
关于java - 如何忽略展开字段 (CSV) 的特定子字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458153/