Java csv file to object

IT Experts

Jackson data format module for reading and writing CSV-encoded data, either as “raw” data (sequence of String arrays ) , or via data binding to/from Java Objects (POJOs).

To use this extension on Maven-based projects, use following dependency:

dependency> groupId>com.fasterxml.jackson.dataformatgroupId> artifactId>jackson-dataformat-csvartifactId> version>2.7.0version> dependency>

Read CSV file based on Java Class.

AS below schema Java Object have explicitly defined Order and properties type to ensured that reading or writing the data in given order.

 package com.example.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonRootName; import java.io.Serializable; import java.math.BigDecimal; /** * Created by MYPC on 7/18/2016. */ @JsonPropertyOrder(value = ) @JsonRootName("transaction") public class Transaction implements Serializable < public enum Currency < INR, HKD, EUR, USD >@JsonProperty private String id; @JsonProperty @JsonFormat(shape = JsonFormat.Shape.NUMBER) private BigDecimal amount; @JsonProperty private Currency currency; public String getId() < return id; >public void setId(String id) < this.id = id; >public double getAmount() < return amount.doubleValue(); >public void setAmount(BigDecimal amount) < this.amount = amount; >public Currency getCurrency() < return currency; >public void setCurrency(Currency currency) < this.currency = currency; >@Override public String toString() < final StringBuffer sb = new StringBuffer("Transaction<"); sb.append("id='").append(id).append('\''); sb.append(", amount=").append(amount); sb.append(", currency color:#3366ff;">/src/main/resources” folder.

id,amount,currency "1001",10000045.999,"EUR" "1002",17777045.999,"HKD" "1003",10000045.999,"USD" "1004",1234045.999,"EUR" "1005",100875.999,"HKD" "1006",165780045.999,"EUR" "1007",32452345.999,"INR" "1008",7777777.999,"EUR"

Reading CSV file to Java Object.

 package com.example; import com.example.model.Transaction; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import java.io.IOException; import java.util.List; /** * Created by MYPC on 7/18/2016. */ public class JSONSchemaReaderApp < public static void main(String[] args) throws IOException < CsvMapper csvMapper = new CsvMapper(); CsvSchema csvSchema = csvMapper.typedSchemaFor(Transaction.class).withHeader(); List list = new CsvMapper().readerFor(Transaction.class) .with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR)) .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv")) .readAll(); for (int i = 0; i < list.size(); i++) < System.out.printf(" Transaction Row [%d] : %s \n", i + 1, list.get(i)); >> > 

Transaction Row [1] : Transaction Transaction Row [2] : Transaction Transaction Row [3] : Transaction Transaction Row [4] : Transaction Transaction Row [5] : Transaction Transaction Row [6] : Transaction Transaction Row [7] : Transaction Transaction Row [8] : Transaction

Reading CSV file into Map

 public static void main(String[] args) throws IOException < CsvMapper csvMapper = new CsvMapper(); CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader(); MappingIteratorMap > it = csvMapper.readerFor(Map.class).with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR)) .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv")); List> listOfMapSchema = it.readAll(); for (Map map : listOfMapSchema) < System.out.println(map); >> 

Источник

Converting CSV to Object in Java

In this blog, we will explore efficient techniques for converting CSV files to Java objects. It covers manual parsing, utilizing external libraries like Apache Commons CSV, and reflection-based mapping. A sample program with outputs is provided, giving you hands-on experience in transforming CSV data into Java objects.

Introduction:

CSV (Comma-Separated Values) files are widely used in software development for data storage and exchange. One common requirement is to convert CSV data into Java objects for further processing and analysis. In this blog, we will explore efficient techniques for converting CSV files to Java objects. We will discuss multiple methods, evaluate their advantages and disadvantages, and provide a sample program that demonstrates the conversion process. By the end, you will have a comprehensive understanding of various approaches and be able to choose the most suitable one for your projects.

Method 1: Manual Parsing

The first method involves manually parsing the CSV file and populating Java objects. Let's consider a simple example where we have a CSV file containing employee data with the following columns: "Name", "Age", and "Salary". We will create a class called Employee to represent the data structure. Here's the sample program that demonstrates manual parsing:

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CSVToObjectConverter < public static void main(String[] args) < String csvFile = "employees.csv"; String line; String csvSplitBy = ","; Listemployees = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) < while ((line = br.readLine()) != null) < String[] data = line.split(csvSplitBy); String name = data[0]; int age = Integer.parseInt(data[1]); double salary = Double.parseDouble(data[2]); Employee employee = new Employee(name, age, salary); employees.add(employee); >> catch (IOException e) < e.printStackTrace(); >for (Employee employee : employees) < System.out.println(employee); >> > class Employee < private String name; private int age; private double salary; public Employee(String name, int age, double salary) < this.name = name; this.age = age; this.salary = salary; >// Getters and setters (omitted for brevity) @Override public String toString() < return "EmployeeCSV. Here's an updated version of our sample program using this library:

import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; public class CSVToObjectConverter < public static void main(String[] args) < String csvFile = "employees.csv"; Listemployees = new ArrayList<>(); try (Reader reader = new FileReader(csvFile); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) < for (CSVRecord csvRecord : csvParser) < String name = csvRecord.get(0); int age = Integer.parseInt(csvRecord.get(1)); double salary = Double.parseDouble(csvRecord.get(2)); Employee employee = new Employee(name, age, salary); employees.add(employee); >> catch (IOException e) < e.printStackTrace(); >for (Employee employee : employees) < System.out.println(employee); >> // Employee class definition (same as in Method 1) > 

Output:

In this approach, we leverage the CSVFormat and CSVParser classes provided by Apache Commons CSV. This library simplifies the parsing process, automatically handles the splitting of fields, and provides convenient methods to access the values.

Method 3: Reflection-Based Mapping

The third method involves using Java's reflection capabilities to map CSV fields directly to object properties. This approach is flexible and reduces manual mapping efforts. Here's an example program that demonstrates reflection-based mapping:

The manual parsing method provides complete control over the parsing process but can be time-consuming and error-prone, especially for larger datasets. External libraries like Apache Commons CSV simplify the conversion process and handle the parsing details for you, reducing manual effort. Reflection-based mapping offers flexibility by dynamically mapping CSV fields to object properties, but it may introduce some performance overhead.

In this blog, we provided a sample program for each method, along with their respective outputs. You can run these programs and observe the successful conversion of CSV data into Java objects. Remember to adjust the code according to your specific CSV structure and object requirements.

Related Post

Источник

Java - how to read CSV file into java object using Jackson CSV library - complex example with BigDecimal and enum

Burhan-Boyce

1. Overview

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

This example contains BigDecimal and enum as ComplexUserDto properties.

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

 com.fasterxml.jackson.dataformat jackson-dataformat-csv 2.9.9 

2. Read CSV file into java object

Below we have all classes we need to read csv file. Ensure to create csv file on your disc and set correct path in ComplexUserCsvReader class.

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

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

  • CsvMapper + CsvSchema from jackson CSV library
  • MappingIterator from jackson databind library
import com.fasterxml.jackson.databind.MappingIterator; 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.List; public class ComplexUserCsvReader < public static void main(String[] args) throws IOException < // set correct path to csv file on your disc File csvFile = new File("C:\\csv_tests\\complex_users.csv"); CsvMapper csvMapper = new CsvMapper(); CsvSchema csvSchema = csvMapper .typedSchemaFor(ComplexUserDto.class) .withHeader() .withColumnSeparator(',') .withComments(); MappingIteratorcomplexUsersIter = csvMapper .readerWithTypedSchemaFor(ComplexUserDto.class) .with(csvSchema) .readValues(csvFile); List complexUsers = complexUsersIter.readAll(); complexUsers.forEach(System.out::println); > >
ComplexUserDto ComplexUserDto ComplexUserDto

2.2 User Pojo object - ComplexUserDto

import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.math.BigDecimal; @JsonPropertyOrder() public class ComplexUserDto < enum Fruit < APPLE, BANANA, ORANGE >private Long id; private String name; private Integer age; private Fruit favouriteFruit; private BigDecimal money; public ComplexUserDto() < >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; >public Fruit getFavouriteFruit() < return favouriteFruit; >public void setFavouriteFruit(Fruit favouriteFruit) < this.favouriteFruit = favouriteFruit; >public BigDecimal getMoney() < return money; >public void setMoney(BigDecimal money) < this.money = money; >@Override public String toString() < return "ComplexUserDtoid,name,age,favouriteFruit,money 1,Ann,30,ORANGE,10001.222 2,Seth,25,APPLE,5550.788 3,Tom,27,BANANA,400.999

References

Источник

Читайте также:  Shopping portal in php
Оцените статью