Home > Java > javaTutorial > body text

Convert CSV to JSON using Jackson library in Java?

WBOY
Release: 2023-08-18 23:49:04
forward
1349 people have browsed it

Convert CSV to JSON using Jackson library in Java?

A Jackson is a Java JSON API that provides many different ways to process JSON. . We can convert CSV data to JSON data using the CsvMapper class, which is a special ObjectMapper with extended functionality that can convert POJOs into CsvSchema instances. We can use the reader() method to build an ObjectReader with default settings. In order to convert, we need to import the com.fasterxml.jackson.dataformat.csv package.

In the example below, convert 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();
      }
   }
}
Copy after login

Output

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

The above is the detailed content of Convert CSV to JSON using Jackson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template