Languages
[Edit]
EN

Java - how to read CSV file into java object with list of numbers using Jackson CSV library

6 points
Created by:
Root-ssh
178170

1. Overview

Edit

In this post we will read CSV file into java pojo object with list of numbers using Jackson CSV processor.

This example contains 2 lists. First list contains Integers, second list contains Doubles.

Lists of Integer and Double in UserWithListsDto class:

  • List<Integer> numbers
  • List<Double> floatingPointNumbers

To use Jackson CSV library we need to add jackson-dataformat-csv dependency to pom.xml.

2. Read CSV file into java object

Edit

Below we have all classes we need to read csv file.

Ensure to create csv file on your disc and set correct path in UserWithListsCsvReader class.

To run this example copy to your project those 3 files:

  1. UserWithListsCsvReader
  2. UserWithListsDto
  3. users_with_numbers_list.csv

How does it work?

  • UserWithListsDto has constructor with 'List<String> csvRow'.
  • In UserWithListsCsvReader we read all lines from csv file and invoke constructor of UserWithListsDto with list of all columns of single line of our csv line.

I didn't find any better solution with this library, so if anyone know better way to do it, post it in comment.

2.1 Logic - UserWithListsCsvReader

Logic which reads CSV file into java UserWithListsDto pojo object with Jackson CSV library.

Usage of classes:

CsvMapper + CsvParser from jackson CSV library
MappingIterator from jackson databind library

Output:

2.2 User Pojo object - UserWithListsDto

2.3 User with numbers list - CSV file

Save this file on disc as 'users_with_numbers_list.csv' and change location in UserWithListsCsvReader class.

2.4 Csv reader util

UserWithListsCsvReaderUtil allows us to read csv from line or convert csv in String to java pojo objects.

Output:
 

References

Edit
  1. jackson-dataformat-csv - maven
  2. Comma-separated values (CSV) - wiki
  3. CsvMapper - JavaDoc
  4. CsvSchema - JavaDoc
  5. MappingIterator - JavaDoc
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join