JSON:
[
{
"to_name":"Voice Portal",
"start_time":"2017-03-14 14:14:46 +0000"
},
{
"to_name":"Voice Portal-1",
"start_time":"2017-03-14 14:14:46 +0000"
},
{
"to_name":"Voice Portal-2",
"start_time":"2017-03-14 14:14:46 +0000"
}
]
代码:
File jsonInputFile = new File("D:\\Java-CallLog\\src\\EdgeNode\\Calllog.json");
InputStream is;
try {
is = new FileInputStream(jsonInputFile);
// Create JsonReader from Json.
JsonReader reader = Json.createReader(is);
// Get the JsonObject structure from JsonReader.
JsonArray callLogArray = reader.readArray();
reader.close();
System.out.println(callLogArray.size());
String csv = null;
File file=new File("D:\\Java-CallLog\\src\\EdgeNode\\Calllog.csv");
for (int i = 0; i<callLogArray.size(); i++){
JsonObject obj = callLogArray.getJsonObject(i);
String name = obj.getString("to_name");
String startTime = obj.getString("start_time");
System.out.println(name);
csv = CDL.toString(obj);
FileUtils.writeStringToFile(file, csv);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
让我知道上面代码中缺少的内容。
是的,我已加入循环。出现以下错误错误:类型CDL中的方法toString(JSONArray)不适用于参数(JsonObject)FileUtils无法解析预期输出:--------------------- Voice Portal,2017-03-14 14:14:46 +0000 Voice Portal-1,2017-03 -14 14:14:46 +0000 Voice Portal-2,2017-03-14 14:14:46 +0000
答案 0 :(得分:0)
文档(https://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/util/CDL.html)表示类CDL的toString()方法需要将org.apache.sling.commons.json.JSONArray作为参数。但是您使用的是javax.json.JsonReader的readArray()方法,它返回一个javax.json.JsonArray。
无论如何,你已经有了名字和startTime作为字符串。这只是给他们所需格式的问题。例如,您可以尝试构建csv字符串。
StringBuilder sb = new StringBuilder();
for(...){
...
sb.append(name).append(",").append(startTime).append(" ");
}
csv = sb.toString();
FileUtils.writeStringToFile(file, csv);
注意writeStringToFile()行在循环之外。