CSV
The org.apache.juneau.marshall.csv package provides a fully-implemented CSV (Comma Separated Values) serializer and parser.
CSV support is included in juneau-marshall.
| Maven | |
|---|
Overview
CSV is an inherently tabular format: each row represents one entry and each column represents one field. Juneau models this as:
| Input type | CSV output |
|---|---|
Collection<Bean> or Bean[] | Header row = property names; one data row per bean. |
Collection<Map> or Map[] | Header row = keys of the first map; one data row per map. |
Collection<SimpleType> or SimpleType[] | Single value column header; one data row per value. |
Single Bean | Header row + one data row. |
Single Map | Header row + one data row. |
Quick Start
// A simple bean
public class Person {
public String name;
public int age;
public Person() {}
public Person(String name, int age) { this.name = name; this.age = age; }
}
// 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);
// Produces:
// name,age
// Alice,30
// Bob,25
// Parse it back
List<Person> parsed = CsvParser.DEFAULT.read(csv, List.class, Person.class);
Or use the convenience marshaller:
String csv = Csv.of(people);
List<Person> parsed = Csv.to(csv, List.class, Person.class);
RFC 4180 Compliance
The serializer and parser comply with RFC 4180:
- Fields containing commas, double-quote characters, or newlines are enclosed in double quotes.
- Double-quote characters inside a quoted field are escaped by doubling them (
""→"). - Both CRLF and LF line endings are accepted on input.
- The Java
nullvalue serializes as the unquoted literalnull.
Null Handling
Java null is serialized as the unquoted string null and is parsed back as Java null.
A Java String with the value "null" is serialized as a quoted "null" to distinguish it.
name,value
null,"null"
The first row's name cell parses back to Java null. The value cell parses back to the Java
String "null".
Swaps
Object swaps registered via .swaps(...) work exactly as with other Juneau serializers/parsers.
Swap classes transform bean property values before serialization and unswap them during parsing.
CsvSerializer s = CsvSerializer.create().swaps(DateSwap.class).build();
CsvParser p = CsvParser.create().swaps(DateSwap.class).build();
Annotations
@CsvConfig applies to both CsvSerializer and CsvParser
on a REST class or method (see Context Annotations). Its only attribute today is rank.
@Csv is a class/method/field marker (its only attribute is description),
and @CsvApply applies it to other
classes/members via on()/onClass() (see Dynamically Applied Annotations).
See Also
- CSV Serializers
- CSV Parsers
- Token-Streaming Basics — CSV is a
PARTIALstreaming format (record cursor only); a CSV row isn't a clean structural token sequence.