Skip to main content

CSV Serializers

The CsvSerializer class is used to serialize POJOs into CSV.

The class hierarchy for the builder of this serializer is:

Context.BuilderMarshallingContextable.BuilderMarshallingTraverseContext.BuilderSerializer.BuilderWriterSerializer.BuilderCsvSerializer.Builder

Refer to the builder javadocs for configurable settings.

The following pre-configured serializers are provided for convenience:

CsvSerializerDEFAULT

Usage​

// Serialize a list of beans to CSV
List<Person> people = List.of(new Person("Alice", 30), new Person("Bob", 25));
String csv = CsvSerializer.DEFAULT.write(people);

// Creates a custom serializer
CsvSerializer s = CsvSerializer.create()
.swaps(DateSwap.class)
.build();
String csv = s.write(people);

// Use the Csv marshaller for convenience
String csv = Csv.of(people);

Output Format​

Beans are serialized as a header row followed by one data row per bean:

public class Person {
public String name;
public int age;
}

List<Person> people = List.of(new Person("Alice", 30), new Person("Bob", 25));
CsvSerializer.DEFAULT.write(people);
name,age
Alice,30
Bob,25

Maps are serialized using the keys of the first map as the header row:

List<Map<String,Object>> rows = List.of(
Map.of("city", "Seattle", "pop", 750000),
Map.of("city", "Portland", "pop", 640000)
);
CsvSerializer.DEFAULT.write(rows);
city,pop
Seattle,750000
Portland,640000

Simple values are serialized with a single value column:

List<String> values = List.of("alpha", "beta", "gamma");
CsvSerializer.DEFAULT.write(values);
value
alpha
beta
gamma

RFC 4180 Quoting​

Values that contain commas, double-quote characters, or newlines are automatically enclosed in double quotes. Double-quote characters inside a quoted value are escaped by doubling them:

List.of(new Person("Smith, John", 40));  // name contains a comma
// Produces: name,age
// "Smith, John",40

List.of(new Person("say \"hi\"", 40)); // name contains quotes
// Produces: name,age
// "say ""hi""",40

Null Values​

Java null is serialized as the unquoted literal null. A Java String with the value "null" is serialized as the quoted string "null" to distinguish it:

new Bean(null, "null")
// Produces: a,b
// null,"null"

Media Type​

CsvSerializer produces output of media type text/csv.