I’m working on a JSON parser which should be able to read valid JSONs from a file, the problem I’m facing is there might be more than on JSON in a file(one line containing multiple JSONs or one JSON in multiple lines), is there any way I could parse it?
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder jsonBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
jsonBuilder.append(line.trim());
if (line.trim().endsWith("}")) {
try (JsonParser jsonParser = Json.createParser(new StringReader(jsonBuilder.toString()))) {
Deque<String> context = new ArrayDeque<>();
StringBuilder currentObject = new StringBuilder();
while (jsonParser.hasNext()) {
Event event = jsonParser.next();
switch (event) {
case START_OBJECT:
context.push("object");
currentObject.append("{");
break;
case END_OBJECT:
context.pop();
currentObject.append("}");
if (context.isEmpty()) {
System.out.println("Parsed JSON: " + currentObject.toString());
currentObject = new StringBuilder();
}
else {
currentObject.append(",");
}
break;
case START_ARRAY:
context.push("array");
currentObject.append("[");
break;
case END_ARRAY:
context.pop();
currentObject.append("]");
break;
case KEY_NAME:
currentObject.append(""").append(jsonParser.getString()).append("":");
break;
case VALUE_STRING:
case VALUE_NUMBER:
currentObject.append(jsonParser.getString());
break;
}
}
}
jsonBuilder.setLength(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
It fetches me complete JSON spanning multiple lines, but couldn’t handle the case of multiple JSON in a single line.
Using javax’s JsonParser
I tried to have an stack which keeps track of the opening and ending of the JSON object, but couldn’t track if multiple JSON are in the same line
manick prime is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1