no

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 us...

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.

Related

java-library 3337423593230609476

Post a Comment Default Comments

2 comments

Unknown said...

This what I am ab;e to see on Console ?Why is the so?

CSVtester.OfferTemplateCategory@91161c7
CSVtester.OfferTemplateCategory@604ed9f0
CSVtester.OfferTemplateCategory@6a4f787b

czetsuya said...

That's the string representation of the object. If you want to show the fields, then override the toString method.

item