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 theresources
directory. - We use the
BufferedReader
andInputStreamReader
to iterate and read theInputStream
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 thetoString()
method of theJSONArray
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 theresources
directory asInputStream
. - Create a
JSONTokener
and provide theInputStream
as argument to its constructor. - Create a
JSONArray
and pass theJSONTokener
object as the constructor argument. - Using
CDL.toString()
we convert theJSONArray
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>