1
我想将我的POJO转换为2个不同的CSV表示形式。杰克逊 - 如何获得视图依赖的CsvSchema?
我的POJO:
@NoArgsConstructor
@AllArgsConstructor
public static class Example {
@JsonView(View.Public.class)
private String a;
@JsonView(View.Public.class)
private String b;
@JsonView(View.Internal.class)
private String c;
@JsonView(View.Internal.class)
private String d;
public static final class View {
interface Public {}
interface Internal extends Public {}
}
}
Public
视图暴露领域a
和b
,并Internal
视图公开所有领域。
问题是,如果我用.writerWithSchemaFor(Example.class)
构建ObjectWriter
,我的所有字段都包含在视图中,但被忽略。 ObjectWriter
将创建Example.class
定义的模式,但如果我应用.withView
它将只隐藏字段,不会忽略它们。
这意味着我必须手动构建模式。
测试:
@Test
public void testJson() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
final Example example = new Example("1", "2", "3", "4");
final String result = mapper.writerWithView(Example.View.Public.class).writeValueAsString(example);
System.out.println(result); // {"a":"1","b":"2"}
}
@Test
public void testCsv() throws JsonProcessingException {
final CsvMapper mapper = new CsvMapper();
final Example example = new Example("1", "2", "3", "4");
final String result = mapper.writerWithSchemaFor(Example.class).withView(Example.View.Public.class).writeValueAsString(example);
System.out.println(result); // 1,2,,
}
@Test
public void testCsvWithCustomSchema() throws JsonProcessingException {
final CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.builder()
.addColumn("a")
.addColumn("b")
.build();
final Example example = new Example("1", "2", "3", "4");
final String result = mapper.writer().with(schema).withView(Example.View.Public.class).writeValueAsString(example);
System.out.println(result); // 1,2
}
testCsv
测试有4个字段,但2被排除在外。 testCsvWithCustomSchema
测试只有我想要的字段。
有没有办法让CsvSchema
与我的@JsonView
相匹配,而无需自己构造它?