EN
Java - how to read CSV file into java object using Jackson CSV library?
5 points
In this post we will read CSV file into java pojo object using Jackson CSV processor.
To use Jackson CSV library we need to add jackson-dataformat-csv dependency to pom.xml.
xxxxxxxxxx
1
<dependency>
2
<groupId>com.fasterxml.jackson.dataformat</groupId>
3
<artifactId>jackson-dataformat-csv</artifactId>
4
<version>2.9.9</version>
5
</dependency>
Below we have all classes we need to read csv file. Ensure to create csv file on your disc and set correct path in UserCsvReader
class.
To run this example copy to your project those 3 files:
- UserCsvReader
- UserDto
- users.csv
2.1 Logic
Logic which reads CSV file into java UserDto pojo object with Jackson CSV library.
Usage of classes:
- CsvMapper + CsvSchema from jackson CSV library
- MappingIterator from jackson databind library
xxxxxxxxxx
1
import com.fasterxml.jackson.databind.MappingIterator;
2
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
3
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
4
5
import java.io.File;
6
import java.io.IOException;
7
import java.util.List;
8
9
public class UserCsvReader {
10
11
public static void main(String[] args) throws IOException {
12
13
// set correct path to csv file on your disc
14
File csvFile = new File("C:\\csv_tests\\users.csv");
15
16
CsvMapper csvMapper = new CsvMapper();
17
18
CsvSchema csvSchema = csvMapper
19
.typedSchemaFor(UserDto.class)
20
.withHeader()
21
.withColumnSeparator(',')
22
.withComments();
23
24
MappingIterator<UserDto> usersIter = csvMapper
25
.readerWithTypedSchemaFor(UserDto.class)
26
.with(csvSchema)
27
.readValues(csvFile);
28
29
List<UserDto> users = usersIter.readAll();
30
31
users.forEach(System.out::println);
32
}
33
}
Output:
xxxxxxxxxx
1
UserDto{id=1, name='Ann', age=30}
2
UserDto{id=2, name='Seth', age=25}
3
UserDto{id=3, name='Tom', age=27}
2.2 User Pojo object - UserDto
xxxxxxxxxx
1
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
2
3
"id", "name", "age"}) ({
4
public class UserDto {
5
6
private Long id;
7
private String name;
8
private Integer age;
9
10
public UserDto() {
11
12
}
13
14
public Long getId() {
15
return id;
16
}
17
18
public void setId(Long id) {
19
this.id = id;
20
}
21
22
public String getName() {
23
return name;
24
}
25
26
public void setName(String name) {
27
this.name = name;
28
}
29
30
public Integer getAge() {
31
return age;
32
}
33
34
public void setAge(Integer age) {
35
this.age = age;
36
}
37
38
39
public String toString() {
40
return "UserDto{" +
41
"id=" + id +
42
", name='" + name + '\'' +
43
", age=" + age +
44
'}';
45
}
46
}
2.3 User CSV file
Save this file on disc as 'users.csv' and change location in UserCsvReader
class.
xxxxxxxxxx
1
id,name,age
2
1,Ann,30
3
2,Seth,25
4
3,Tom,27