How to parse a JSON File without root element using org.json.simple?

淺唱寂寞╮ 提交于 2019-12-11 02:05:55

问题


I want to parse json file "c:/employeesRecord.json" using org.json.simple library. Below is sample json data, each record is sperated by next line in the file.

{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
...

How to parse such json file without root element using org.json.simple.


回答1:


You can "tweak" the input from the file and change it into a valid json format

String json = <your json from file>
json = "[" + json + "]";
json = json.replace("\n",",");
// parse your json, now it should be a valid.



回答2:


Since the full file is not a valid JSON object you will need to parse it line-by-line, ie. read first line, parse it using your parser, save the result and then repeat for the next line.




回答3:


Parse it line by line after spliting by \n.

String[] lines = json.split("\n");
List<JsonObject> objects = new ArrayList<>(lines.length); // depending on the JSON library you are using

for(String line : lines) {
    objects.add(parseJson(line));
}


来源:https://stackoverflow.com/questions/41397606/how-to-parse-a-json-file-without-root-element-using-org-json-simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!