java - 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);
让我知道是否需要任何细节。谢谢
解决方案
看一下代码:
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
推荐阅读
- google-cloud-platform - 如何在 GCE 上禁用 windows server 2016 自动更新
- unity3d - MRTK V2 - Toggle-Dot 移动到约束之外
- node.js - 如何判断 TLS 服务器是否请求了客户端证书
- android - Volley Post Request ClientError
- python-3.x - 运行以下代码而不会出现超时错误
- python - 如何获取列表的第一列?
- django - django 的模型的 save() 方法如何知道在 db 表中保存的位置?
- linux - 循环使用扩展名的文件不起作用
- php - PHP 合并 json 文件
- python - 为什么 SCK、MOSI 和 MISO 引脚连接到橙色 pi 零时总是挂在高电平?