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.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-csv</artifactId>
        <version>2.17.1</version>
    </dependency>    
</dependencies>

Maven Central Maven Central Maven Central Maven Central

How do I convert CSV file to or from JSON file?

In the following code snippet you will see how to convert a CSV file into JSON file and vice versa. We use the JSON-Java library CDL class to convert between CSV and JSON format. The CDL class provide the toJSONArray(String) and toString(JSONArray) methods that allows us to do the conversion between data format.

In the CSV file, the first line in the file will be used as the keys to the generated JSON string. On the other way around, the JSON string keys will be written on the first line of the CSV file as the column header.

Convert CSV file to JSON file.

package org.kodejava.json;

import org.json.CDL;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.stream.Collectors;

public class CsvFileToJsonFile {
    public static void main(String[] args) {
        // Read csv data file and store it in a string
        InputStream is = CsvFileToJsonFile.class.getResourceAsStream("/data.csv");
        String csv = new BufferedReader(
                new InputStreamReader(Objects.requireNonNull(is), StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));

        try {
            // Convert csv text to JSON string, and save it 
            // to a data.json file.
            String json = CDL.toJSONArray(csv).toString(2);
            Files.write(Path.of("data.json"), json.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What we do in the snippet above:

  • Get cvs data as InputStream from the resources directory.
  • We use the BufferedReader and InputStreamReader to iterate and read the InputStream and return it as a string.
  • Convert the csv string into JSON string using CDL.toJSONArray().
  • We can pretty-printed the JSON string by specifying an indentFactor to the toString() method of the JSONArray object.
  • Write the JSON string to a file.

Here is the data.csv file example.

id,first_name,last_name,email,gender,ip_address
1,Abe,Foord,[email protected],Female,81.38.18.88
2,Editha,Castagnaro,[email protected],Genderqueer,181.63.39.199
3,Tildie,Furminger,[email protected],Male,0.199.18.3

Convert JSON file to CSV file.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

public class JsonFileToCsvFile {
    public static void main(String[] args) {
        // Get data.json resource as InputStream, create JSONTokener
        // and convert the tokener into JSONArray object.
        InputStream is = JsonFileToCsvFile.class.getResourceAsStream("/data.json");
        JSONTokener tokener = new JSONTokener(Objects.requireNonNull(is));
        JSONArray jsonArray = new JSONArray(tokener);

        try {
            // Convert JSONArray into csv and save to file
            String csv = CDL.toString(jsonArray);
            Files.write(Path.of("data.csv"), csv.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What we do in the code snippet above:

  • Get data.json from the resources directory as InputStream.
  • Create a JSONTokener and provide the InputStream as argument to its constructor.
  • Create a JSONArray and pass the JSONTokener object as the constructor argument.
  • Using CDL.toString() we convert the JSONArray object to csv text.
  • Finally, save the csv into file using Files.write().

And here is the data.json JSON file example.

[
  {
    "id": "1",
    "first_name": "Abe",
    "last_name": "Foord",
    "email": "[email protected]",
    "gender": "Female",
    "ip_address": "81.38.18.88"
  },
  {
    "id": "2",
    "first_name": "Editha",
    "last_name": "Castagnaro",
    "email": "[email protected]",
    "gender": "Genderqueer",
    "ip_address": "181.63.39.199"
  },
  {
    "id": "3",
    "first_name": "Tildie",
    "last_name": "Furminger",
    "email": "[email protected]",
    "gender": "Male",
    "ip_address": "0.199.18.3"
  }
]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I convert CSV into JSON string using JSON-Java?

In this example we convert CSV or CDL into JSON string. We are going to use the JSON-Java CDL (Comma Delimited Text) class. This class provides static methods that will convert a CSV into JSONArray or to convert a JSONArray into comma separated values.

Here are what we do in the code snippet below:

  • Create a comma delimited text. The first line is the headers, this will be the keys in our JSON string. The couples lines is the values. We use the Java text blocks feature to define the string.
  • Create JSONArray object by calling CDL.toJSONArray() static method as pass the comma delimited string as argument.
  • Next we create a JSONArray object, but we separate the header and the body. We do this by calling the CDL.toJSONArray() and provides headers and countries as arguments.
  • Last, we call the CDL.toString() method with JSONArray as argument to convert it to comma delimited text.

Let’s see the code in action.

package org.kodejava.json;

import org.json.CDL;
import org.json.JSONArray;

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
                """;

        // Convert comma delimited text into JSONArray object.
        JSONArray jsonCountries = CDL.toJSONArray(countries);
        System.out.println(jsonCountries.toString(2));

        // Using a separate header and values to create JSONArray
        // from a comma delimited text
        JSONArray header = new JSONArray();
        header.put("ISO");
        header.put("CODE");
        header.put("NAME");

        countries = """
                CZE, CZ, CZECH REPUBLIC\s
                DNK, DK, DENMARK\s
                DJI, DJ, DJIBOUTI\s
                DMA, DM, DOMINICA\s
                ECU, EC, ECUADOR
                """;

        jsonCountries = CDL.toJSONArray(header, countries);
        System.out.println(jsonCountries.toString(2));

        // Convert back from JSONArray to comma delimited text
        countries = CDL.toString(jsonCountries);
        System.out.println(countries);
    }
}

Running the code produces the following results.

To JSON string:

[
  {
    "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"
  }
]

Back to CSV

ISO,CODE,NAME
CZE,CZ,CZECH REPUBLIC
DNK,DK,DENMARK
DJI,DJ,DJIBOUTI
DMA,DM,DOMINICA
ECU,EC,ECUADOR

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central