Reading a JSON file in Java using Jackson Databind to generate data classes
Assuming you are using IntelliJ
-
Create a new project (File -> New -> Project, then select Maven)
-
(Optional but a good habit!) Make a git repository
git init .
-
Add libraries:
- Open the pom.xml file, right click and choose "generate... -> Dependency"
- Suggested libraries:
- jackson-databind, for JSON to data classes
- jackson-module-parameter-names, for binding immutable classes with Jackson
- guava, for lots of useful libs including the Preconditions class
- lombok, for boilerplate reduction (probably skip this if you're not already familiar with it)
- If you are using lombok with jackson-databind, looks like you need the setting I've added in lombok.config
- commons-math3, often useful in speed coding for least common multiple, prime testing, nCr and so on
- com.google.truth, pretty assertions like assertThat(x).isEqualTo(y)
-
Generate typed classes for our example JSON file
- Create the data mapping classes. Use an inner class to keep everything in one file, or split it out for ease of navigation:
@Value static class MenuRoot { List<MenuItem> menu; } @Value static class MenuItem { String dishName; int cost; }
- Let's add code to read in the JSON file and deserialize it into our structure:
String input = Resources.toString(Resources.getResource("genericSample.json"), StandardCharsets.UTF_8); MenuRoot menu = objectMapper.readValue(input, MenuRoot.class);
-
Finally let's do something with the data we've read:
System.out.println("Today's menu:"); System.out.println("----"); for (MenuItem menuItem : menu.menu) { System.out.printf("%1$-30s £%s\n", menuItem.dishName, menuItem.cost); }
and run the project by clicking the "run" icon next to the main method