首页 > 解决方案 > Json 数组列表转 CSV 格式

问题描述

我正在以所需的格式将 JSON 对象转换为 CSV 转换。我尝试了多种方法..但没有看。任何观点将不胜感激。

Here is the output I am getting when I get convert JSON object to JSON Array.
         JSONObject jsonObj = new JSONObject(content.toString());

         JSONArray docs = jsonObj.getJSONArray("Results");

          System.out.println("get the array"+docs);

输出结果现在在这里。

get the array
[
 {"Item":1,"Status":"Approved","Name":"Brownie","SubmitDate":"2016-04-05T14:06:16Z","ReceivedState":1},
 {"Item":3,"Status":"Approved","Name":"Oats","SubmitDate":"2016-04-19T19:39:25Z","ReceivedState":1},
 {"Item":2,"Status":"Submitted","Name":"Choclate","SubmitDate":"2016-06-01T12:40:19Z","ReceivedState":1},
 ]

现在我期待以 csv 格式输出以下格式

Item,Status,Name,SubmittedDate,ReceivedState
1,Approved,Brownie,"2016-04-05T14:06:16Z",1
3,Approved,Oats,"2016-04-19T19:39:25Z",1
2,Submitted,Choclate,"016-06-01T12:40:19Z",1

下面的代码有例外:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:0

我知道是因为我们在这里将 ArrayList 存储在文档中。我不确定如何进一步转换为预期的 CSV 格式。如果有人可以指导将不胜感激。

File file = new File("C:\\MYVIEW.csv"); 
         String csv =CDL.toString(docs); 
         FileUtils.writeStringToFile(file, csv);

让我知道是否需要任何细节。谢谢

标签: javaarraysjsoncsvarraylist

解决方案


看一下代码:

public static void main(String[] args) throws IOException {
    String inputJson = "{Results: [\n" +
            " {\"Item\":1,\"Status\":\"Approved\",\"Name\":\"Brownie\",\"SubmitDate\":\"2016-04-05T14:06:16Z\",\"ReceivedState\":1},\n" +
            " {\"Item\":3,\"Status\":\"Approved\",\"Name\":\"Oats\",\"SubmitDate\":\"2016-04-19T19:39:25Z\",\"ReceivedState\":1},\n" +
            " {\"Item\":2,\"Status\":\"Submitted\",\"Name\":\"Choclate\",\"SubmitDate\":\"2016-06-01T12:40:19Z\",\"ReceivedState\":1},\n" +
            " ]}";
    JSONObject jsonObj = new JSONObject(inputJson);
    JSONArray objJsonArray = jsonObj.getJSONArray("Results");
    String csv = CDL.toString(objJsonArray);
    System.out.println(csv);
    FileUtils.writeStringToFile(new File(System.getenv("HOME")+ "/temp.csv"), csv);
}

输出

Status,Item,SubmitDate,ReceivedState,Name
Approved,1,2016-04-05T14:06:16Z,1,Brownie
Approved,3,2016-04-19T19:39:25Z,1,Oats
Submitted,2,2016-06-01T12:40:19Z,1,Choclate

推荐阅读