How do I convert CSV to JSON string using Jackson?

In the following code snippet we will convert CSV into JSON string using Jackson JSON library. A comma-separated values is a delimited text, it uses comma to separate values. It starts with header on the first line, that will be the JSON key. Each subsequence lines is the data of the csv, which also contains several values separated by comma.

Let’s see the code how to do this in Jackson.

package org.kodejava.jackson;

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

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

public class CsvToJson {
    public static void main(String[] args) {
        // Comma delimited text created using text blocks
        String countries = """
                ISO, CODE, NAME\s
                CZE, CZ, Czech Republic\s
                DNK, DK, Denmark\s
                DJI, DJ, Djibouti\s
                DMA, DM, Dominica\s
                ECU, EC, Ecuador
                """;

        CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();

        try {
            List<Map<?, ?>> list;
            try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader()
                    .forType(Map.class)
                    .with(csvSchema)
                    .readValues(countries)) {
                list = mappingIterator.readAll();
            }

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonPretty = objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(list);
            System.out.println(jsonPretty);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the explanation of the code above:

  • Define a csv string, in this case we have a list of countries.
  • Create an empty schema of CsvSchema to process csv with header line.
  • Create an instance of CsvMapper, a specialized type of ObjectMapper.
  • Read and parse csv values into List<Map<?, ?>>.
  • We use the ObjectMapper create a pretty-printed JSON from the list object.

Running the code produces the following output:

[ {
  "ISO" : "CZE",
  "CODE" : " CZ",
  "NAME" : " Czech Republic "
}, {
  "ISO" : "DNK",
  "CODE" : " DK",
  "NAME" : " Denmark "
}, {
  "ISO" : "DJI",
  "CODE" : " DJ",
  "NAME" : " Djibouti "
}, {
  "ISO" : "DMA",
  "CODE" : " DM",
  "NAME" : " Dominica "
}, {
  "ISO" : "ECU",
  "CODE" : " EC",
  "NAME" : " Ecuador"
} ]

Maven Dependencies

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

Maven Central Maven Central Maven Central Maven Central

Wayan

3 Comments

  1. Hi,
    When I try to run the code you mentioned, I am getting the errors. The method readAll() is undefined for the type MappingIterator<Map>. The method forType(Class) is undefined for the type ObjectReader.

    May I know how to resolve these errors?

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.