Jackson is a popular Java library for processing JSON, XML, and CSV data. Many developers choose Jackson because it offers powerful features and strong community support. Although Jackson is mainly known for JSON, it also provides excellent tools for handling CSV.
To work with CSV in Jackson, you need the jackson-dataformat-csv
module. This module extends Jackson’s capabilities and makes CSV handling easy.
Setting Up Your Java Project
First, you need to add the required dependency. If you are using Maven, add the following to your pom.xml
file:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-csv --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-csv</artifactId> <version>2.19.0</version> </dependency>
After adding the dependency, refresh your project to download the library.
Creating a Java Class for Your Data
You need a simple Java class representing the data structure to read and write CSV files. Here is an example:
import lombok.*; @Getter @Setter @AllArgsConstructor @ToString @RequiredArgsConstructor public class User { private String name; private int age; private String email; }
This User
class has three fields: name, age, and email. It also includes the necessary getters and setters.
Reading a CSV File Using Jackson
Sample Data
age,email,name 28,alice@example.com,Alice 34,bob@example.com,Bob
Let’s read a CSV file and map it to Java objects.
import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import java.io.File; import java.util.List; public class CsvReaderExample { public static void main(String[] args) throws Exception { CsvMapper mapper = new CsvMapper(); CsvSchema schema = mapper.schemaFor(User.class).withHeader(); File file = new File("D:/jackson_csv/user.csv"); List<User> users = mapper.readerFor(User.class) .with(schema) .<User>readValues(file) .readAll(); users.forEach(System.out::println); } }
In this example:
- We create a
CsvMapper
instance. - We define a
CsvSchema
based on theUser
class. - We read the CSV file and put it into a list of
User
objects.
Each line in the CSV file is automatically mapped to a User
object.
Reading CSV by Position Without Headers Using Jackson
If your CSV file has no headers (just raw values like):
28,alice@example.com,Alice 34,bob@example.com,Bob
Now, read the CSV by column position, not by header:
public class ReadCsvByPosition { public static void main(String[] args) throws Exception { CsvMapper mapper = new CsvMapper(); // Manually define the schema (no header!) CsvSchema schema = CsvSchema.builder() .addColumn("age", CsvSchema.ColumnType.NUMBER) .addColumn("email") .addColumn("name") .setUseHeader(false) // Very important: no headers .build(); File file = new File("D:/jackson_csv/user.csv"); MappingIterator<User> it = mapper .readerFor(User.class) .with(schema) .readValues(file); List<User> users = it.readAll(); users.forEach(System.out::println); } }
Key Points:
.setUseHeader(false)
Tells Jackson not to expect headers..addColumn()
maps the order: first column →name
, second →age
, third →email
.- You must define the columns manually to match the file order.
Example Output:
User(name=Alice, age=28, email=alice@example.com) User(name=Bob, age=34, email=bob@example.com)
Writing a CSV File Using Jackson
Next, how to write Java objects to a CSV file.
import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import java.io.File; import java.util.Arrays; import java.util.List; public class CsvWriterExample { public static void main(String[] args) throws Exception { List<User> users = Arrays.asList( new User("Alice", 28, "alice@example.com"), new User("Bob", 34, "bob@example.com") ); CsvMapper mapper = new CsvMapper(); CsvSchema schema = mapper.schemaFor(User.class).withHeader(); File file = new File("D:/jackson_csv/user.csv"); mapper.writer(schema).writeValue(file, users); System.out.println("CSV file written successfully."); } }
Here:
- We create a list of users.
- We create a
CsvSchema
with headers. - We write the list to a file using the mapper.
The resulting CSV file will have name, age, and email columns.
Tips for Working with Jackson CSV
Here are a few essential tips when working with Jackson and CSV files:
- Always define a proper schema.
- Make sure your class fields match the CSV headers.
- Handle exceptions carefully when reading and writing files.
- Validate your data before writing to avoid errors.
Handling Custom Column Names
Sometimes, your CSV headers do not match your Java field names. Jackson allows you to map CSV columns to Java fields using annotations.
Example:
import com.fasterxml.jackson.annotation.JsonProperty; public class Employee { @JsonProperty("Full Name") private String name; @JsonProperty("Years") private int experience; // Getters and Setters }
By using @JsonProperty
You can map the CSV column “Full Name” to the name
field and “Years” to experience
.
Parsing CSV Without Headers
If your CSV file does not have headers, you can adjust the schema like this:
CsvSchema schema = CsvSchema.emptySchema().withColumnSeparator(',').withoutHeader();
Always define the column order properly when reading or writing files without headers.
Conclusion
Jackson makes working with CSV files in Java very easy. You can map CSV data directly into Java objects and write Java objects to CSV format. Using the proper schema, annotations, and practices ensures a smooth workflow.
By mastering Jackson CSV processing, you can handle real-world data problems efficiently. Whether you manage small datasets or extensive records, Jackson provides a fast and reliable solution.