Wednesday, February 9, 2011

How To Read A Csv File Alongside Header Inwards Coffee Using Jackson Library - Event Tutorial

Hello guys, today I am going to demo you lot how to read a CSV file inward Java amongst a uncomplicated representative of Jackson API. For a long time, I exclusively knew that Jackson tin live used to parse JSON but later on realized that you lot tin also utilisation it to parse or read CSV file inward Java. The Jackson DataFormat CSV library allows you lot to read a CSV file inward only a couplet of problem in addition to its actually powerful in addition to characteristic rich. For example, you lot tin read a CSV file amongst a header or without a header. You tin fifty-fifty read a tab-delimited text file similar CSV. It's also highly configurable in addition to allows you lot to define columns separator to read a text file amongst whatever delimiter. You tin fifty-fifty utilisation it to straight convert the CSV information into Java objects, only similar nosotros do piece reading JSON String inward Java.

For a long time, I was similar DIY guy i.e. I would similar to code everything I involve in addition to that's why I e'er receive got that large Utility course of study inward my every Java projection but things changed after reading the Effective Java.

The mass is total of best practices in addition to smashing practical advice from Joshua Bloch, writer of Java Collection framework in addition to many primal classes on the java.lang package. In ane of the items on Effective Java, he advised that you lot should e'er utilisation libraries for the mutual chore instead of re-inventing the bike in addition to from so I receive got non looked back.

Same is truthful for reading or parsing CSV file inward Java. If you lot await at my before solution, it wasn't a production fix solution. I receive got demonstrated how you lot tin utilisation BufferedReader to read a CSV file but it doesn't handgrip many corner cases similar wagon supply inward values, whatever plain protected yesteryear quotes, etc. It was also non optimized for performance.

When you lot utilisation a tried in addition to tested in addition to proven library you lot acquire all these benefits yesteryear default in addition to that's the principal argue I enquire Java developers to acquire themselves familiar amongst essential in addition to useful Java libraries. I receive got shared around 20 most useful Java libraries before in addition to I am encouraging my readers to advise equally well, if you lot haven't read that article yet, you lot should read it now.




How to parse a CSV file amongst column header inward Java using Jackson

Anyway, let's come upwards dorsum to the topic. In this article, I'll demo you lot how to read a CSV file using the Jackson library inward Java.

Suppose nosotros receive got next CSV file which contains the title, author, in addition to toll of popular online courses for Java developers.

Title,Author,Price REST With Spring,Eugen Paraschiv, 290 Learn Spring Security,Baeldung,290 Complete Java MasterClass,Udemy,200

Actually, I was tired amongst the mass examples I e'er use, so, I used online courses this time, but they are some of the actually best courses in addition to if you lot are interested inward Java then The Complete Java Masterclass is ane of the best course of study to start with, experience complimentary to bring together them.

 I exclusively knew that Jackson tin live used to  How to read a CSV file amongst Header inward Java using Jackson library -  Example Tutorial


Now, to stand upwards for this information inward our Java application, I receive got created a course of study called OnlineCourse, which looks similar below:

class OnlineCourse{   private String title;   private String author;   private int price;      ...     public OnlineCourse(){      // no declaration constructor required yesteryear Jackson   }   }

I receive got omitted other constructors, getter, in addition to setter for readability in addition to you lot tin also do if you lot utilisation the Lombok library. It has both pros in addition to cons but that's a topic for some other day.

Just shout out upwards that Jackson utilisation reflection thus a default no-argument constructor is mandatory inward your class.

Now, we'll write code to read this CSV file inward Java in addition to re-create the objects into ArrayList or only impress them into the console.


This is what you lot involve to read the CSV file using Jackson:

CsvMapper csvMapper = new CsvMapper(); CsvSchema schema = CsvSchema.emptySchema().withHeader();    ObjectReader oReader = csvMapper.reader(OnlineCourse.class).with(schema); try (Reader reader = new FileReader("file.txt")) {     MappingIterator<OnlineCourse> mi = oReader.readValues(reader);     while (mi.hasNext()) {       System.out.println(current);     } }

Influenza A virus subtype H5N1 CsvMapper is a course of study which maps information from CSV to Java objects piece CsvSchema defines Schema similar whether CSV has a header or not. You tin also specify if a file is comma separated or tab delimited, which we'll come across inward the adjacent article.

This volition impress next inward the console:

EBook [title=REST With Spring, author=Eugen Paraschiv, price=290] EBook [title=Learn Spring Security, author=Baeldung, price=290] EBook [title=Complete Java MasterClass, author=Udemy, price=200

Which agency our plan is successfully read the CSV file. If you lot desire you lot tin shop the objects into a List or Map as good equally we'll do inward our sample program. Btw, if you lot are non familiar amongst essential Collection classes similar those so delight come across immutable in addition to fully reusable (as are ObjectWriter instances).

import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List;   import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema;   /* * Java Program to iterate over JSONObject of json-simple */ public class JacksonTest {   public static void main(String args[]) throws FileNotFoundException, IOException {      CsvMapper csvMapper = new CsvMapper();     CsvSchema schema = CsvSchema.emptySchema().withHeader();        ObjectReader oReader = csvMapper.reader(OnlineCourse.class).with(schema);     List<OnlineCourse> courses = new ArrayList<>();        try (Reader reader = new FileReader("file.txt")) {            MappingIterator<OnlineCourse> mi = oReader.readValues(reader);            while (mi.hasNext()) {                  OnlineCourse electrical flow = mi.next();                  courses.add(current);                  System.out.println(current);       } }      System.out.println("number of courses into list: " + courses.size());   }   }     class OnlineCourse{ private String title; private String author; private int price;    public OnlineCourse(){     // no declaration constructor required yesteryear Jackson }   public OnlineCourse(String title, String author, int price) {     this.title = title;     this.author = author;      this.price = price; }   public String getTitle() {     return title; }   public String getAuthor() {    return author; }   public int getPrice() {    return price; }     public void setTitle(String title) {    this.title = title; }   public void setAuthor(String author) {    this.author = author; }   public void setPrice(int price) {    this.price = price; }     @Override public String toString() {      return "EBook [title="How to read a CSV file amongst Header inward Java using Jackson library -  Example Tutorial"color: #000040;">+ championship + ", author=" + writer + ", price="                               + toll + "]";   }    }   Output: EBook [title=REST With Spring, author=Eugen Paraschiv, price=290] EBook [title=Learn Spring Security, author=Baeldung, price=290] EBook [title=Complete Java MasterClass, author=Udemy, price=200] release of courses into list: 3

You tin come across that nosotros receive got successfully converted a CSV file into a bunch of Java object. Each problem which is aught but a CSV String forthwith represents a Java object. If you lot desire to larn to a greater extent than virtually Jackson, I advise you lot accept a await at the JSON amongst Java APIs in addition to REST Web Services course of study on Udemy.

 I exclusively knew that Jackson tin live used to  How to read a CSV file amongst Header inward Java using Jackson library -  Example Tutorial



Common Errors

Nothing is slow inward this earth in addition to if you lot do something the outset time, you lot are jump to acquire some obstacles in addition to that's truthful amongst parsing a CSV file using Jackson equally well.

Exception inward thread "main" java.lang.VerifyError: Cannot inherit from lastly class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.fasterxml.jackson.dataformat.csv.CsvMapper.<init>(CsvMapper.java:39)
at JacksonTest.main(JacksonTest.java:25)


Cause in addition to Solution

This fault puzzled me a piffling combat but I rapidly realize that it has something to do amongst incompatible versions because an fault is coming from the Jackson library itself. That was indeed the case, I was using jackson-dataformat-csv-2.9.jar but I had jackson-core-2.2.3.jar inward my classpath. After using jackson-dataformat-csv-2.2.jar the fault goes away automatically.

In short, brand certain that all your Jackson components receive got the same pocket-size fry version: amongst dataformat-csv 2.9.jar you lot MUST utilisation jackson-core in addition to jackson-databind of 2.9 equally well.

Btw, it's amend to utilisation tools similar Maven or Gradle which volition do dependency administration for you, instead of you lot downloading Jackson JAR manually.




Another error:
at [Source: java.io.FileReader@3b81a1bc; line: 2, column: 16] (through reference chain: OnlineCourse["Title"])
at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:122)
at JacksonTest.main(JacksonTest.java:34)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized plain "Title" (class OnlineCourse), non marked equally ignorable (3 known properties: , "title", "price", "author"])
at [Source: java.io.FileReader@3b81a1bc; line: 2, column: 16] (through reference chain: OnlineCourse["Title"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:189)
at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:120)
... 1 more


Reason:
When you lot parse CSV information using Jackson it's similar parsing JSON which agency your belongings should precisely tally amongst the fields inward your class. It's also case-sensitive. In our case, the plain inward the course of study is called "title" piece inward the CSV file header is called "Title" thus error, after sorting that this fault has gone.


That's all virtually how to read a CSV file inward Java using Jackson DataFormat CSV API. You tin slow it's real slow to that. The Jackson library is both powerful in addition to feature-rich in addition to allows you lot to configure CSVSchema inward multiple ways which agency you lot tin read CSV file amongst header (first line), without header, values amongst quotes inward it, in addition to problem intermission on values.

You tin fifty-fifty read a tab-delimited text file using this library. I'll part some to a greater extent than examples of Jackson DataFormat CSV library but till so do whatever you lot desire to do but don't problem your woman bring upwards :-)

Further Learning 
Master Java Web Services in addition to REST API amongst Spring Boot
REST API Design, Development & Management
tutorial)
  • 5 JSON libraries Java JEE Programmer should know (list)
  • Why utilisation Spring to do REST API inward Java? (article)
  • How to parse JSON amongst appointment plain inward Java using Jackson? (tutorial)
  • How to convert JSON array to String array inward Java using Gson? (tutorial)
  • 6 Courses to larn Spring inward depth (courses)
  • How to Escape JSON String inward Eclipse (tips)
  • How to ignore Unknown properties piece parsing JSON inward Java? (tutorial)
  • How to download the Jackson library for JSON parsing? (tutorial)
  • How to convert JSON Array to String Array inward Java? (tutorial)
  • How to parse a large JSON file using Jackson Streaming API? (example)
  • How to utilisation Google Protocol Buffer (protobuf) inward Java? (tutorial)
  • Top five courses to larn Spring kick inward depth (courses)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the piece of employment of unlike HTTP methods inward REST? (see here)
  • 5 Courses to larn RESTFul Web Services inward Java? (courses)

  • Thanks for reading this article so far. If you lot similar this Jackson tutorial to parse CSV file inward Java so delight part amongst your friends in addition to colleagues. If you lot receive got whatever questions or feedback so delight drib a note. 

    P. S. - If you lot are novel to Java in addition to looking for some complimentary courses to start amongst so you lot tin also depository fiscal establishment check out this listing of free Java Courses for Beginners. Join them before they expire.

    No comments:

    Post a Comment