忽略 CSV 和 JSON 中的不同字段

Ignore different fields in CSV and JSON

我有 s Spring REST API 通常只输出 JSON.

现在我还想为某些端点导出 CSV。

Jackson 有一个图书馆

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-csv</artifactId>
    <version>2.8.5</version>
</dependency>

我可以使用 Spring 的 HttpMessageConverter

但是我需要排除 JSON 中存在的 CSV 中的某些字段,因此我无法使用 @JsonIgnore 注释。有没有办法对 CSV 使用不同的忽略 property/annotation?

作为替代方案,我考虑使用自定义界面来提取值以预先序列化这些值。 List<CSVableDTO> -> List<Map<String,?>> -> CSV。但我想避免这种情况,因为它涉及额外的实例创建和额外的编码,而不是仅使用新的注释。

Java-Class-示例:

public class MyDTO {

    @CSVIgnore
    public int id;
    public String name;
    public String property;
    @CSVIgnore
    public String ref;

}

JSON-示例:

[
    {
        "id": 42,
        "name": "Example",
        "property": "FooBar",
        "ref": "42:Not:FooBar:1337"
    }
]

预期 CSV 结果:

"name";"property"
"Example";"FooBar"

请考虑使用 JsonView mechanism。你会有这样的东西:

public class Foo {

     public interface JsonOnly{}
     public interface CsvView{}

     @JsonView(JsonOnly.class) 
     private Integer secretNotForCsv;

     // ...

}

@RestController
public class FooController {

       @RequestMapping(...)
       @JsonView(Foo.JsonOnly.class)
       public Foo getJson() {
           // ...
       }

       @RequestMapping(...)
       @JsonView(Foo.CsvView.class)
       public Foo getCsv() {
           // ...
       }
}

这只是一个非常粗略的草图,但它应该能让您有所了解。