我解析FileReader期间,文件意外的令牌结尾在位置0错误

时间:2019-10-01 11:32:14

标签: java json parsing

我第一次使用代码时总是会遇到一些麻烦,但我不明白为什么。我使用监视程序服务来控制文件夹。一旦一个新文件(包含JSON中的数据)进入该文件夹,我就会对其进行解析以进行处理。从第一次解析开始,我在位置0处出现错误的意外令牌END OF FILE。有时也会发生,但是我感觉是随机的。

我已经在寻找另一种方法,我找不到...

这是json文件的示例:

{"identifier":"004","note":null,"addresses":null,"msgType":"Alert","code":null,"references":null,"source":null,"sent":"2018-01-17T22:39:00-07:00","sender":"test","scope":"Public","restriction":null,"incidents":null,"status":"Actual","info":{"severity":"Severe","area":null,"audience":null,"expires":null,"resource":null,"certainty":"Likely","description":null,"language":null,"onset":null,"eventCode":null,"effective":null,"responseType":null,"senderName":"Los Angeles Police Dept - LAPD","urgency":"Immediate","web":null,"instruction":null,"contact":null,"parameter":{"valueName":"Beeldvorming","value":"<b>Time: 2019-09-07T15:44:54-00:00<\/b>  Sender: Fire DepartmentMessage: Hello007"},"category":"Rescue","event":"Child Abduction","headline":"Amber Alert in Los Angeles County"}}

这是我解析此Json的Java代码:

while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
        if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
            String fileName = event.context().toString();
            try {
                String absolutePath = lcmsFolderPath + fileName;
                FileReader fileReader = new FileReader(absolutePath);
                // If unexpected token end of file at position 0
                // == parse used twice.
                JSONObject jsonObject = (JSONObject) parser
                        .parse(fileReader);
                JSONObject infoJson = (JSONObject) jsonObject.get("info");
                JSONObject parameterJson = (JSONObject) infoJson.get("parameter");
                String htmlValue = (String) parameterJson.get("value");
                String valueName = (String) parameterJson.get("valueName");
                fileReader.close();

                if (htmlValue != null) {
                    createLCMSDocument(valueName, htmlValue);
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
        }
    }
    key.reset();
}

谢谢

0 个答案:

没有答案