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

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.

COMMENTS

mas template
Name

amazon,1,angular,8,bigdata,2,business,1,course-spring,27,courses,6,database,4,docker,3,java,50,kafka,1,keycloak,4,microservices,5,mysql,1,neworking,1,nosql,2,php,1,pinned,2,react,3,server management,7,shared drive,1,spring,7,synology,1,troubleshooting,2,web,1,wordpress,1,
ltr
item
toztech: How to read and write csv using jackson library
How to read and write csv using jackson library
toztech
https://toztech.blogspot.com/2017/03/how-to-read-and-write-csv-using-jackson.html
https://toztech.blogspot.com/
https://toztech.blogspot.com/
https://toztech.blogspot.com/2017/03/how-to-read-and-write-csv-using-jackson.html
true
2554149350007112447
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content