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 callingCDL.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 theCDL.toJSONArray()
and providesheaders
andcountries
as arguments. - Last, we call the
CDL.toString()
method withJSONArray
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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024