我正在编写一个应用程序,以接受来自Json文件的输入并对它进行排序。我有一个函数,该函数接受JsonObjects的已排序ArrayList并将它们写入到临时文件中(稍后在外部合并排序中使用)。我遇到的问题是,当JsonGenerator将最终的JsonObject写入文件时,它会在输出期间突然退出,从而使文件未完成且无法使用。
我尝试启用漂亮的打印,更改示例文件的大小,再次检查JsonObjects的ArrayList中的数据是否正确。没事。
这是有问题的函数:
public void writeTempDataToFile(ArrayList<JsonObject> jsobs, File file){
try {
FileOutputStream fos = new FileOutputStream(file);
JsonGeneratorFactory jsonGeneratorFactory = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
JsonGenerator jWrite = jsonGeneratorFactory.createGenerator(fos);
jWrite.writeStartObject();
jWrite.writeStartArray("results");
for(JsonObject jsob : jsobs){
jWrite.writeStartObject();
jsob.forEach((key, value) -> {
jWrite.write(key, value);
});
jWrite.writeEnd();
}
jWrite.writeEnd();
jWrite.writeEnd();
fos.close();
} catch (Exception ex) {System.out.println(ex);}
}
这是我稍后在执行外部合并排序期间读取不完整的JsonObject时收到的错误消息。错误期间执行的操作是将不完整的JsonObject添加到
的ArrayList中JsonObjects.
javax.json.stream.JsonParsingException: Invalid token=EOF at (line no=411011, column no=7671, offset=19889551). Expected tokens are: [STRING]
这是输出的样本。第一个JsonObject是它的外观,第二个是要写入的最终对象,它显示了输出突然停止的位置。
{
"classification": "Class II",
"center_classification_date": "20121025",
"report_date": "20121031",
"postal_code": "08816-2108",
"termination_date": "20141007",
"recall_initiation_date": "20120904",
"recall_number": "D-031-2013",
"city": "East Brunswick",
"event_id": "63384",
"distribution_pattern": "Nationwide",
"openfda": {
},
"recalling_firm": "Raritan Pharmaceuticals, Inc.",
"voluntary_mandated": "Voluntary: Firm Initiated",
"state": "NJ",
"reason_for_recall": "Microbial Contamination of Non-Sterile Products: Product is being recalled due to possible microbial contamination by C. difficile discovered in the raw material.",
"initial_firm_notification": "E-Mail",
"status": "Terminated",
"product_type": "Drugs",
"country": "United States",
"product_description": "Premier Value Fiber Plus Calcium Supplement Capsules, 120 capsules per bottle, Distributed by: Chain Drug Consortium, LLC, Boca Raton, FL, UPC 8-40986-01987-6",
"code_info": "Lot 15087, Exp 08/15",
"address_1": "8 Joanna Ct",
"address_2": "",
"product_quantity": "96 bottles"
},
{
"classification": "Class II",
"center_classification_date": "20121025",
"report_date": "20121031",
"postal_code": "08816-2108",
"termination_date": "20141007",
"recall_initiation_date": "20120904",
"recall_number": "D-026-2013",
"city": "East Brunswick",
"event_id": "63384",
"distribution_pattern": "Nationwide",
"openfda": {
},
"recalling_firm": "Raritan Pharmaceuticals, Inc.",
"voluntary_mandated": "Volun
我希望输出是一个完整的Json文件,且所有括号都闭合。
答案 0 :(得分:1)
您需要在关闭FileOutputStream之前关闭JsonGenerator(很可能是使用需要刷新的内部字符缓冲区)。