Posted In: Jackson 2X, JSON

Converting CSV to JSON using Jackson library

Maven Jackson 2X

<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-csv</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.0</version>
</dependency>

Classes used

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
package com.example.csv;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class CsvToJson {

	@Test
	public void csvtojson() throws Exception {
		System.out.println("csvtojson started");
		File input = new File("E:/files/incsv.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();
		}
	}
}

Tags: Tags:

by , on August 31st, 2017