Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java - how to write java object to CSV file using Jackson CSV library

0 contributions
1 points

1. Overview

In this post we will save java object into CSV file using Jackson CSV processor.

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

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-csv</artifactId>
    <version>2.9.9</version>
</dependency>

2. Write java object to CSV file

Below we have 2 classes we need to save simple UserDto java class to CSV file.
Ensure to set correct path and filename as output.

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

  1. UserCsvWriter
  2. UserDto

2.1 Logic

Logic which saves UserDto java pojo object to CSV file with Jackson CSV library.

Usage of classes:

  • CsvMapper + CsvSchema from jackson CSV library
  • ObjectWriter from jackson databind library
  • JsonGenerator from jackson core
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserCsvWriter {

    public static void main(String[] args) throws IOException {

        // set correct directory as output
        File csvOutputFile = new File("C:\\csv_tests\\user_output.csv");

        UserDto userDto1 = new UserDto(1L, "Ann", 30);
        UserDto userDto2 = new UserDto(2L, "Seth", 28);
        UserDto userDto3 = new UserDto(3L, "Emm", 24);

        List<UserDto> list = new ArrayList<>(Arrays.asList(userDto1, userDto2, userDto3));

        CsvMapper mapper = new CsvMapper();
        mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);

        CsvSchema schema = CsvSchema.builder().setUseHeader(true)
                .addColumn("id")
                .addColumn("name")
                .addColumn("age")
                .build();

        ObjectWriter writer = mapper.writerFor(UserDto.class).with(schema);

        writer.writeValues(csvOutputFile).writeAll(list);

        System.out.println("Users saved to csv file under path: ");
        System.out.println(csvOutputFile);
    }
}

Output:

Users saved to csv file under path:
C:\csv_tests\user_output.csv

2.2 User Pojo object - UserDto

import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"id", "name", "age"})
public class UserDto {

    private Long id;
    private String name;
    private Integer age;

    public UserDto() {

    }

    public UserDto(Long id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserDto{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

References

  1. jackson-dataformat-csv - maven
  2. Comma-separated values (CSV) - wiki
  3. CsvMapper - JavaDoc
  4. CsvSchema - JavaDoc
  5. ObjectWriter - JavaDoc
  6. JsonGenerator - JavaDoc
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more