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 pretty print JSON string in JSON-Java?

In JSON-Java we can make a pretty-printed JSON string by specifying an indentFactor to the JSONObject‘s toString() method. The indent factor is the number of spaces to add to each level of indentation.

If indentFactor > 0 and the JSONObject has only one key, the JSON string will be printed a single line, and if the JSONObject has 2 or more keys, the JSON string will be printed in multiple lines.

Let’s create a pretty-printed JSONObject text using the code below.

package org.kodejava.json;

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

public class PrettyPrintJSON {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        JSONArray courses = new JSONArray(
                new String[]{"Engineering", "Finance"});
        jsonObject.put("courses", courses);

        // Default print without indent factor
        System.out.println(jsonObject);

        // Pretty print with 2 indent factor
        System.out.println(jsonObject.toString(2));
    }
}

Running this code produces the following output:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
{
  "courses": [
    "Engineering",
    "Finance"
  ],
  "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 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 read values from JSONObject?

A JSONObject is an unordered collection of key-value pairs. To read values from the JSONObject we can use the get(String key) and opt(String key) methods. These generic methods return an Object, which you can cast to a certain type.

There are also typed get and opt methods to read value in specific type such as getString(), getInt(), getDouble(), optString(), optFloat(), optBigInteger(), optBoolean(), optEnum(), etc. For more detail, you can check the JSONObject API documentation.

The get methods throws JSONException when the key is not found in the JSONObject, while the opt methods does not throw exception but return null, and we can also pass a default value argument that will be returned when the key is not found.

The code below give you a simple example to read values from JSONObject.

package org.kodejava.json;

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

public class ReadJSONValue {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 1L);
        jsonObject.put("name", "Alice");
        jsonObject.put("age", 20);
        jsonObject.put("courses",
                new JSONArray(new String[] {"Engineering", "Finance"}));
        System.out.println(jsonObject);

        // Using get() and opt() methods we need to cast
        // the returned value to the type its store.
        long id1 = (long) jsonObject.get("id");
        String name1 = (String) jsonObject.get("name");
        int age1 = (int) jsonObject.get("age");
        JSONArray courses1 = (JSONArray) jsonObject.get("courses");

        // This will throw exception because JSONObject
        // does not have the address key in it.
        String address1;
        try {
            address1 = (String) jsonObject.get("address");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Using opt() method to read address, does not throw
        // exception
        address1 = (String) jsonObject.opt("address");

        System.out.println("id1      = " + id1);
        System.out.println("name1    = " + name1);
        System.out.println("age1     = " + age1);
        System.out.println("address1 = " + address1);
        System.out.println("courses1 = " + courses1);
        System.out.println();

        // Using data type specific get() and opt() methods.
        // We don't have to cast the return from the getXXX()
        // and optXXX() methods.
        long id2 = jsonObject.getLong("id");
        String name2 = jsonObject.getString("name");
        int age2 = jsonObject.optInt("age");

        // Using optString() to read address and provide default
        // value when address is not found.
        String address2 = jsonObject.optString("address", "No Address");
        JSONArray courses2 = jsonObject.optJSONArray("courses");

        System.out.println("id2      = " + id2);
        System.out.println("name2    = " + name2);
        System.out.println("age2     = " + age2);
        System.out.println("address2 = " + address2);
        System.out.println("courses2 = " + courses2);
    }
}

Running this code produces the following results:

{"courses":["Engineering","Finance"],"name":"Alice","id":1,"age":20}
org.json.JSONException: JSONObject["address"] not found.
    at org.json.JSONObject.get(JSONObject.java:580)
    at org.kodejava.json.ReadJSONValue.main(ReadJSONValue.java:28)

id1      = 1
name1    = Alice
age1     = 20
address1 = null
courses1 = ["Engineering","Finance"]

id2      = 1
name2    = Alice
age2     = 20
address2 = No Address
courses2 = ["Engineering","Finance"]

Maven Dependencies

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

Maven Central