如何忽略展开字段的特定子字段(CSV)

时间:2018-03-23 20:53:11

标签: java csv jackson jackson2

如何告诉Jackson跳过未打开的子POJO字段,这样当我解析为CSV时,它会跳过整个列?

这是一个完整的代码示例:

-vvv

请注意,我无法以任何方式修改课程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。我只是想跳过这一栏。

1 个答案:

答案 0 :(得分:1)

使用:@JsonIgnoreProperties({ "toBeIgnoredA", "toBeIgnoredB" })

public class ToSerialize {
  @JsonUnwrapped(prefix = "toBeUnwrapped")
  @JsonIgnoreProperties({ "toBeIgnoredA", "toBeIgnoredB" })
  public ToBeUnwrapped toBeUnwrapped;
}

或(很长的路)为ToBeUnwrapped创建包装类,您可以在其中自由配置JSON注释,而不会触及实际的ToBeUnwrapped