How to read and write csv using jackson library
Tech-Today

How to read and write csv using jackson library


The sample code below demonstrates how we can read a csv file into an array of objects. Also it writes an array of objects into csv.

To use don't forget to include in your pom.xml

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

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

/**
* @author Edward P. Legaspi
**/
public class CsvTest {

private final String FILE_NAME = "offerTemplateCategory.csv";

public static void main(String args[]) {
try {
CsvTest app = new CsvTest();
app.testCsvRead();
app.testCsvWrite();
} catch (Exception e) {
e.printStackTrace();
}
}

private void testCsvRead() throws Exception {
System.out.println("read csv");

// load file from resource
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(FILE_NAME).getFile());

// configure the schema we want to read
CsvSchema schema = CsvSchema.builder().addColumn("parentCategoryCode").addColumn("code").addColumn("name").addColumn("description").build();
CsvMapper mapper = new CsvMapper();

// configure the reader on what bean to read and how we want to write
// that bean
ObjectReader oReader = mapper.readerFor(OfferTemplateCategory.class).with(schema);

// read from file
try (Reader reader = new FileReader(file)) {
MappingIterator mi = oReader.readValues(reader);
while (mi.hasNext()) {
System.out.println(mi.next());
}
}
}

private void testCsvWrite() throws Exception {
// initialize our list
List list = new ArrayList<>();
list.add(populateOfferCat(1));
list.add(populateOfferCat(2));
list.add(populateOfferCat(3));

// initialize and configure the mapper
CsvMapper mapper = new CsvMapper();
// we ignore unknown fields or fields not specified in schema, otherwise
// writing will fail
mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);

// initialize the schema
CsvSchema schema = CsvSchema.builder().addColumn("parentCategoryCode").addColumn("code").addColumn("name").addColumn("description").build();

// map the bean with our schema for the writer
ObjectWriter writer = mapper.writerFor(OfferTemplateCategory.class).with(schema);

File tempFile = new File("c://temp//output.csv");
// we write the list of objects
writer.writeValues(tempFile).writeAll(list);
}

/**
* Initialize an OfferTemplateCategory using index as suffix.
*
* @param index
* @return
*/
private OfferTemplateCategory populateOfferCat(int index) {
OfferTemplateCategory o1 = new OfferTemplateCategory();
o1.setParentCategoryCode("PARENT_" + index);
o1.setCode("CAT_" + index);
o1.setName("CAT_NAME_" + index);
o1.setDescription("CAT_DESCRIPTION_" + index);

return o1;
}

}

Just create your OfferTemplateCategory class with the fields in schema (parentCategoryCode, code, name, description). Maybe add another field unknown. Try to remove mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true) and you'll see the error I've mentioned.




- How To Use Xpath To Read Nodes From Xml File
XPath is a java library that let us read a complicated xml document with ease. In our simple example below we have an xml that contains computers with some random tags like os. <computers> <windows> <lenovo model="g50"> <year>2015</year>...

- Rest Testing With Arquillian In Jboss
This article will explain how we can automate REST web service testing using Arquillian and JBoss web server. First, you must create a javaee6 war (non-blank) project from jboss-javaee6 archetype. This should create a project with Member model, service,...

- Create A Custom Json String Deserializer In Java
On normal cases we really have a lot of ways in doing so, we can use jaxb, jackson and more. But in some cases we really need to improvised, for example in the project I'm working right now I have a date string from a .net application in this format:...

- How To Get Started With Hibernate In Java. Create A Simple Class And Database Schema For Demostration.
Since, I've always been using different database sometimes I get confused how to implement the others. Like hibernate, where the configuration must be properly set. *This help assumes that you have already created a java project in eclipse that has...

- How To Create A Java Application That Can Read And Write To An Excel's (microsoft Office) And Calc's (open Office) Worksheet
Requirements: -JOpenDocument: http://www.jopendocument.org/downloads.html (calc worksheet api) -Excel POI: http://poi.apache.org/download.html (excel worksheet api) -JUnit: http://sourceforge.net/project/showfiles.php?group_id=15278&package_id=12472...



Tech-Today








.