📜  org.json-CDL

📅  最后修改于: 2020-11-12 05:07:52             🧑  作者: Mango


CDL类提供静态方法,以逗号分隔的文本转换为JSONArray,反之亦然。

示例中涵盖了以下方法。

  • rowToJSONArray(String) -将逗号分隔的文本转换为JSONArray对象。

  • rowToString(JSONArray) -将JSONArray转换为逗号分隔的文本。

  • toJSONArray(String) -将多行逗号分隔的文本转换为JSONArray对象的Object。

  • toJSONArray(JSONArray,String) -将JSONArray对象和逗号分隔的文本转换为JSONArray对象。

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));

      //Case 3: CSV to JSONArray of Objects
      csvData = "empId, name, age \n" +
         "1, Mark, 22 \n" +
         "2, Robert, 35 \n" +
         "3, Julia, 18";
      System.out.println(CDL.toJSONArray(csvData));

      //Case 4: CSV without header        
      jsonArray = new JSONArray();
      jsonArray.put("empId");
      jsonArray.put("name");
      jsonArray.put("age");
      csvData = "1, Mark, 22 \n" + "2, Robert, 35 \n" + "3, Julia, 18";
      System.out.println(CDL.toJSONArray(jsonArray,csvData));
   }
}

输出

["INDIA","UK","USA"]
INDIA,UK,USA

[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]
[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]