3

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.

7
  • Split your string/buffer by newline (.split("\n")) and parse them one by one?
    – SOFe
    Dec 30, 2016 at 14:13
  • Would you like to show me an example? Dec 30, 2016 at 14:14
  • For Android using Gson it is solved in link Dec 30, 2016 at 14:18
  • 2
    You are encouraged to post your own solutions as answers to your question.
    – SOFe
    Dec 30, 2016 at 14:20
  • Yes my json is not valid but i need to process such files. Thanks @PEMapModder your solution works for. Dec 31, 2016 at 12:31

3 Answers 3

3

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.
0
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.

0
1

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));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.