1 回答

TA貢獻1780條經驗 獲得超5個贊
抱歉,遲到的回復在過去 30 分鐘內一直在敲我的鍵盤,但我終于完成了,這是代碼。
public static String getCSVData() throws IOException, JSONException {
Path jsonFile = Paths.get("json");
String json = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(json.trim());
List<List<String>> jsonArrays = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
List<String> jsonObjects = new ArrayList<>();
JSONArray record = jsonArray.getJSONObject(i).getJSONArray("record");
for (int i2 = 0; i2 < record.length(); i2++) {
JSONObject jsonObject = record.getJSONObject(i2);
if (i2 == 0) {
jsonObjects.add(jsonObject.get("timeStamp").toString());
jsonObjects.add(jsonObject.get("code").toString());
jsonObjects.add(jsonObject.get("text").toString());
} else {
jsonObjects.add(jsonObject.get("hostname").toString());
jsonObjects.add(jsonObject.get("address").toString());
jsonObjects.add(jsonObject.get("type").toString());
jsonObjects.add(jsonObject.get("priority").toString());
jsonObjects.add(jsonObject.get("ttl").toString());
}
}
jsonArrays.add(jsonObjects);
}
StringBuilder stringBuilder = new StringBuilder("timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl\n");
for(List<String> arrays : jsonArrays){
stringBuilder.append(StringUtils.join(arrays, ",")).append("\n");
}
return stringBuilder.toString().trim();
}
為了解釋代碼,我首先遍歷第一個數組,然后獲取第一個 JSONArray 的 jsonObject,然后從我通過遍歷第一個 JSONArray 得到的 JsonObject 中獲取名為“record”的 jsonArray,然后遍歷 record 并獲取所有項并將它們保存到 ArrayList 中。并通過 JDK 提供的 StringUtils 加入它們。
如果你想把它寫到文件中,請使用這個
Files.write(Paths.get("YOUR CSV FILE"), getCSVData().getBytes(StandardCharsets.UTF_8));
我使用的所有代碼都是由 JDK 和 org.json 提供的。
在我們打印出 getCSVDate(); 輸出是:
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,3600,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
添加回答
舉報