Reading JSON in Java

During the past few days I have had multiple interviews, and we all know how some technical interviews can feel overly rigid, but that’s a discussion for another time. For this specific interview I was asked to read a JSON and do different actions on it e.g. average sum. While the problems themselves were not hard, I cannot say the same for reading a JSON in Java.

Spoiler alert I did not pass the interview, because I ran out of time, most of it being spent reading a JSON file in Java.

*Note:* for the sake of simplicity I am going to omit the imports.

Reading JSON from local file

1
2
3
4
5
List<String> allLines = Files.readAllLines(Paths.get("file.json"));
String jsonContent = String.join("\n", allLines);

ObjectMapper om = new ObjectMapper();
var mappedJson = om.readValue(jsonContent, JsonModel[].class);

As we can see it is not so straight forward as in just referencing the file and passing it to the object mapper, but we have to actually concatenate all new lines in a single line, otherwise it will fail properly reading it and you will end up with a bunch of errors.

And there is another way that is similar, but that requires referencing the file, reading the output in a loop and joining through a StringBuilder, but let’s be honest, that is too verbose for reading only 1 file for an interview, unless you also have some tricky optimizations to perform.

Reading JSON from URL

There is a neat trick that I found after the interview, and that is we can directly reference a URL to the object mapper, instead of having to deal with any files handling.

1
2
ObjectMapper om = new ObjectMapper();
var mappedJson = om.readValue(URI.create("https://example.com/json").toURL(), JsonModel[].class);

Reading JSON from String

The most simple way is just passing the string to the read value along with the model, but believe me this does not scale. I was given a file with millions of fields, and long story short Intellij was not happy and it froze.

1
2
ObjectMapper om = new ObjectMapper();
var mappedJson = om.readValue("{\"jsonModel\":\"value\"}", JsonModel.class);

Conclusion

Reading JSON in Java can be frustrating, especially under pressure, but it’s a skill worth mastering. Jackson is powerful once you get the hang of it, so take some time to practice before your next challenge. And hey, every interview is a learning experience—better luck next time!