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,afoord0@harvard.edu,Female,81.38.18.88
2,Editha,Castagnaro,ecastagnaro1@nih.gov,Genderqueer,181.63.39.199
3,Tildie,Furminger,tfurminger2@hud.gov,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": "afoord0@harvard.edu",
    "gender": "Female",
    "ip_address": "81.38.18.88"
  },
  {
    "id": "2",
    "first_name": "Editha",
    "last_name": "Castagnaro",
    "email": "ecastagnaro1@nih.gov",
    "gender": "Genderqueer",
    "ip_address": "181.63.39.199"
  },
  {
    "id": "3",
    "first_name": "Tildie",
    "last_name": "Furminger",
    "email": "tfurminger2@hud.gov",
    "gender": "Male",
    "ip_address": "0.199.18.3"
  }
]

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </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>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I create JSONArray object?

A JSONArray object represent an ordered sequence of values. We use the put() method to add or replace values in the JSONArray object. The value can be of the following types: Boolean, JSONArray, JSONObject, Number, String or the JSONObject.NULL object.

Beside using the put() method we can also create and add data into JSONArray in the following ways:

  • Using constructor to create JSONArray from string wrapped in square bracket [], where the values are separated by comma. JSONException maybe thrown if the string is not a valid JSON string.
  • Creating JSONArray by passing an array as an argument to its constructor, for example an array of String[].
  • Using constructor to create JSONArray from a Collection, such as an ArrayList object.

The following example show you how to create JSONArray object.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CreateJSONArray {
    public static void main(String[] args) {
        // Create JSONArray and put some values
        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Java");
        jsonArray.put("Kotlin");
        jsonArray.put("Go");
        System.out.println(jsonArray);

        // Create JSONArray from a string wrapped in bracket and
        // the values separated by comma. String value can be 
        // quoted with single quote.
        JSONArray colorArray = new JSONArray("[1, 'Apple', 2022-02-07]");
        System.out.println(colorArray);

        // Create JSONArray from an array of String.
        JSONArray stringArray =
                new JSONArray(new String[]{"January", "February", "March"});
        System.out.println(stringArray);

        // Create JSONArray by passing a List to its constructor
        List<String> list = new ArrayList<>();
        list.add("Red");
        list.add("Green");
        list.add("Blue");
        JSONArray listArray = new JSONArray(list);
        System.out.println(listArray);

        // Using for loop to get each value from the array
        for (int i = 0; i < listArray.length(); i++) {
            System.out.println("Color: " + listArray.get(i));
        }

        // Put JSONArray into a JSONObject.
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("colors", listArray);
        System.out.println(jsonObject);
    }
}

Running the code above produces the following result:

["Java","Kotlin","Go"]
[1,"Apple","2022-02-07"]
["January","February","March"]
["Red","Green","Blue"]
Color: Red
Color: Green
Color: Blue
{"colors":["Red","Green","Blue"]}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I write JSON string using JSON-Java (org.json) library?

The following code snippet show you how to create JSON string using JSON-Java library. Create an instance of JSONObject and use the put() method to create a key-value pair for the JSON string. The JSONArray object can be used to create an array of list of values to the JSON string, we also use the put() method to add value to the list.

The JSONObject.toString() method accept parameter called indentFactor, this set the indentation level of the generated string, which also make the JSON string generated easier to read and look prettier.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;

public class WriteJSONString {
    public static void main(String[] args) {
        JSONObject object = new JSONObject();
        object.put("id", 1L);
        object.put("name", "Alice");
        object.put("age", 20);

        JSONArray courses = new JSONArray();
        courses.put("Engineering");
        courses.put("Finance");
        courses.put("Chemistry");

        object.put("courses", courses);

        String jsonString = object.toString(2);
        System.out.println(jsonString);
    }
}

The result of the code snippet above is:

{
  "courses": [
    "Engineering",
    "Finance",
    "Chemistry"
  ],
  "name": "Alice",
  "id": 1,
  "age": 20
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central

How do I read JSON file using JSON-Java (org.json) library?

In this example we are going to use the JSON-Java (org.json) library to read or parse JSON file. First we start by getting the InputStream of the JSON file to be read using getResourceAsStream() method. Next we construct a JSONTokener from the input stream and create an instance of JSONObject to read the JSON entries.

We can use method like getString(), getInt(), getLong(), etc. to read a key-value from the JSON file. The getJSONArray() method allow us to read a list of values returned in JSONArray object, which can be iterated to get each values represented by the key. Let’s see the detail code snippet below.

package org.kodejava.json;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;

public class ReadJSONString {
    public static void main(String[] args) {
        // info.json
        // {
        //   "id": "1",
        //   "name": "Alice",
        //   "age": "20",
        //   "courses": [
        //     "Engineering",
        //     "Finance",
        //     "Chemistry"
        //   ]
        // }
        String resourceName = "/info.json";
        InputStream is = ReadJSONString.class.getResourceAsStream(resourceName);
        if (is == null) {
            throw new NullPointerException("Cannot find resource file " + resourceName);
        }

        JSONTokener tokener = new JSONTokener(is);
        JSONObject object = new JSONObject(tokener);
        System.out.println("Id  : " + object.getLong("id"));
        System.out.println("Name: " + object.getString("name"));
        System.out.println("Age : " + object.getInt("age"));

        System.out.println("Courses: ");
        JSONArray courses = object.getJSONArray("courses");
        for (int i = 0; i < courses.length(); i++) {
            System.out.println("  - " + courses.get(i));
        }
    }
}

The result of the code snippet above is:

Id  : 1
Name: Alice
Age : 20
Courses: 
  - Engineering
  - Finance
  - Chemistry

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
        <type>bundle</type>
    </dependency>
</dependencies>

Maven Central