[Java] Add quotes only to specific CSV columns

background

--I'm trying to create a CSV output function in Spring --The base was created immediately by imitating this article.

Task

--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.

counter-measure

--Set all String types to have quotes --Add @JsonRawValue to columns you don't want to add quotes

sample

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

[Java] Add quotes only to specific CSV columns
Add class only to specific elements with V-for
Map only specific columns to POJO by searching using Repository
Add multi-letter watermark to Java Word
How to add columns to a table
Add watermark to Java to PDF document
[Java] Add WordArt to Word document
Add / remove watermark to Java PowerPoint
kotlin & Java: How to hide the toolbar only for specific fragments
[Java] How to add data to List (add, addAll)
Java (add2)
Java (add)
Add Document to Azure Search Service (Java)
Add footnotes to Word documents in Java
Add SameSite attribute to cookie in Java
How to add / remove Ruby on Rails columns
[Java] How to get random numbers excluding specific numbers
[Java] Article to add validation with Spring Boot 2.3.1.
[Java] Introduction to Java
Introduction to java
PKIX path building failed: Add SSL certificate to java
Use Maven to add your favorite Java library to your environment.
I want to apply ContainerRelativeShape only to specific corners [SwiftUI]
[Java] How to erase a specific character from a character string
[Java] [XML signature] Add prefix and ID to Signature tag
[IOS] To allow rotation of only a specific screen