Convert CSV to JSON using the Jackson library in Java?


A Jackson is a Java JSON API that provides several different ways to work with JSON. We can convert CSV data to JSON data using the CsvMapper class, it is specialized ObjectMapper, with extended functionality to produce CsvSchema instances out of POJOs. We can use the reader() method for constructing ObjectReader with default settings. In order to convert this, we need to import the com.fasterxml.jackson.dataformat.csv package.

In the below example, convert a CSV to JSON.

Example

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.dataformat.csv.*;
public class CsvToJsonTest {
   public static void main(String args[]) throws Exception {
      File input = new File("input.csv");
      try {
         CsvSchema csv = CsvSchema.emptySchema().withHeader();
         CsvMapper csvMapper = new CsvMapper();
         MappingIterator<Map<?, ?>> mappingIterator =  csvMapper.reader().forType(Map.class).with(csv).readValues(input);
         List<Map<?, ?>> list = mappingIterator.readAll();
        System.out.println(list);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

[{last name=Chandra, first name=Ravi, location=Bangalore}]

Updated on: 06-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements