Reputation: 2707
I have s Spring REST API that usually just outputs JSON.
Now I want to also export CSVs for some endpoints.
Jackson has a library for that
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.8.5</version>
</dependency>
Which I can utilize using Spring's HttpMessageConverter
.
However I need to exclude some fields in the CSV that are present in the JSON thus I cannot use @JsonIgnore
annotation. Is there a way to use a different ignore property/annotation for CSV?
As an alternative i considered using a custom interface to extract the values to serialize the values before hand. List<CSVableDTO>
-> List<Map<String,?>>
-> CSV. But I would like to avoid that because it involves extra instance creation and extra coding vs just using a new annotation.
Java-Class-Example:
public class MyDTO {
@CSVIgnore
public int id;
public String name;
public String property;
@CSVIgnore
public String ref;
}
JSON-Example:
[
{
"id": 42,
"name": "Example",
"property": "FooBar",
"ref": "42:Not:FooBar:1337"
}
]
Expected-CSV-Result:
"name";"property"
"Example";"FooBar"
Upvotes: 2
Views: 1684
Reputation: 34900
Please, consider usage of JsonView
mechanism. You will have something like that:
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() {
// ...
}
}
This is only a very rough sketch, but it should give you an idea.
Upvotes: 1