--I'm trying to create a CSV output function in Spring --The base was created immediately by imitating this article.
--I want to add quotes only to specific columns in CSV ――After a little research, I could only add or not add quotes to all String type columns.
--Set all String types to have quotes
--Add @JsonRawValue
to columns you don't want to add quotes
SampleController.java
@RestController
public class SampleController {
@GetMapping(value="/sample.csv", produces="text/csv;charset=utf-8;Content-Disposition:attachment")
public String csv() throws JsonProcessingException {
List<UserBean> rows = new ArrayList<UserBean>() {
{
add(new UserBean("ozaki", "runners", 27));
}
};
CsvMapper mapper = new CsvMapper();
//If you add withHeader, a header will be added to the first line.
CsvSchema schema = mapper.schemaFor(UserBean.class).withHeader();
// ALWAYS_QUOTE_If STRINGS is used, String type columns will have quotes.
mapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
return mapper.writer(schema).writeValueAsString(rows);
}
}
UserBean.java
//Set the order of CSV columns
@JsonPropertyOrder({"name", "team", "age"})
public class UserBean {
private String name;
//Quarts are not attached with JsonRawValue
@JsonRawValue
private String team;
private Integer age;
public UserBean(String name, String team, Integer age) {
this.name = name;
this.team = team;
this.age = age;
}
/* setter/getter */
sample.csv
"name","team","age"
"ozaki",runners,27
Recommended Posts