【发布时间】:2020-02-06 06:43:00
【问题描述】:
我一直在尝试从 pdf 文件中读取 JSON。我可以将 JSON 字符串写入 pdf,但是当我阅读 pdf 时,我收到如下错误。
原因:com.google.gson.stream.MalformedJsonException:未终止 对象位于第 60 行第 3 列路径 $.All_Routes[0].route_data
我在写入文件之前打印了 JSON,并使用 JSON 验证器在线验证它,它是有效的 JSON,但在我写入到 pdf 之后,它变成了 无效。我只是从 pdf 复制 JSON 并在线验证它,但它没有经过验证并给出错误。
这是将 JSON 写入 pdf 文件的代码。
try {
File file = AppUtils.createFile(".pdf");
Document document = new Document();
document.setPageSize(PageSize.A4);
document.addCreationDate();
document.addAuthor("Me");
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
String jsonBody = new Gson().toJson(backUpModel);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonBody);
String prettyJsonBody = gson.toJson(jsonElement);
Log.i(Constants.TAG, "Input Json: " + prettyJsonBody);
document.add(new Paragraph(prettyJsonBody));
document.close();
//Toast.makeText(BackUp.this, "Saved Succesfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
这是读取 PDF 文件的代码。
try {
File exportDir = new File(Environment.getExternalStorageDirectory(), Constants.TAG);
String filePath = exportDir.getPath() + File.separator + getFileName(fileUri);
PdfReader pdfReader = new PdfReader(filePath);
int numberOfPages = pdfReader.getNumberOfPages();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <= numberOfPages; i++) {
stringBuilder.append(PdfTextExtractor.getTextFromPage(pdfReader, i));
}
pdfReader.close();
String jsonBody = stringBuilder.toString();
BackUpModel backUpModel = new Gson().fromJson(jsonBody, BackUpModel.class);
} catch (IOException e) {
e.printStackTrace();
}
谁能建议我解决这个问题的可能解决方案?
谢谢
【问题讨论】:
-
“我一直在尝试从 pdf 文件中读取 JSON” - 你是如何尝试的?当您将读取的文本与原始 json 进行比较时,它们有何不同?
-
@mkl 您可以从上述链接中获取 JSON。您可以使用jsonformatter.curiousconcept.com 对其进行验证或比较
-
@mkl 我添加了从 PDF 文件读取 JSON 的代码。
-
您的问题是
new Paragraph():添加的换行符和额外空间。new Paragraph()是一种抽象,可以自行处理空间、段落等内容。您需要手动执行此操作才能写出完美的JSON -
这么说,可能在原始json包含空格的地方出现了一些换行,而这些空格在整个过程中可能会丢失。因此,我的问题是替代方法是否也可以工作......