Org.Json - CSV Examples
Org.Json - Cookie Examples
Org.Json - HTTP Header Examples
Org.Json - JSON Examples
Org.Json - Property Examples
Org.Json - XML Examples
Org.Json - Exception Handling
Org.Json - Useful Resources
Org.Json - CDL Class
CDL class provides static methods to convert a comma delimited text into a JSONArray, and vice versa.
Following methods are covered in the example.
rowToJSONArray(String) − Converts a comma delimited text to JSONArray Object.
rowToString(JSONArray) − Converts a JSONArray to comma delimited text.
toJSONArray(String) − Converts a multi-line comma delimited text to Object of JSONArray objects.
toJSONArray(JSONArray, String) − Converts a JSONArray Object and comma delimited text to JSONArray Object.
Example - Conversion of CSV data to JSON Array and Vice Versa
JsonDemo.java
package com.tutorialspoint;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;
public class JsonDemo {
public static void main(String[] args) {
String csvData = "INDIA, UK, USA";
//Case 1: CSV to JSON Array
JSONArray jsonArray = CDL.rowToJSONArray(new JSONTokener(csvData));
System.out.println(jsonArray);
//Case 2: JSONArray to CSV
System.out.println(CDL.rowToString(jsonArray));
}
}
Output
["INDIA","UK","USA"] INDIA,UK,USA
Example - Conversion of CSV data with headers to JSON Array of Objects
JsonDemo.java
package com.tutorialspoint;
import org.json.CDL;
public class JsonDemo {
public static void main(String[] args) {
//Case 3: CSV to JSONArray of Objects
String csvData = "empId, name, age \n" +
"1, Mark, 22 \n" +
"2, Robert, 35 \n" +
"3, Julia, 18";
System.out.println(CDL.toJSONArray(csvData));
}
}
Output
[{"name":"Mark","empId":"1","age":"22"},{"name":"Robert","empId":"2","age":"35"},{"name":"Julia","empId":"3","age":"18"}]
Example - Conversion of JSON Array to CSV without headers
JsonDemo.java
package com.tutorialspoint;
import org.json.CDL;
import org.json.JSONArray;
public class JsonDemo {
public static void main(String[] args) {
//Case 4: CSV without header
JSONArray jsonArray = new JSONArray();
jsonArray.put("empId");
jsonArray.put("name");
jsonArray.put("age");
String csvData = "1, Mark, 22 \n" + "2, Robert, 35 \n" + "3, Julia, 18";
System.out.println(CDL.toJSONArray(jsonArray,csvData));
}
}
Output
[{"name":"Mark","empId":"1","age":"22"},{"name":"Robert","empId":"2","age":"35"},{"name":"Julia","empId":"3","age":"18"}]
Advertisements