In this tutorial, we are taking a look at a student's question from my Spring Boot Introduction Course.
In this chapter, we will create a Spring Batch application which uses an MySQL Reader and a Flatfile Writer (.txt ). Reader − The Reader we are using in the application is JdbcCursorItemReader to read data from MySQL database. Assume we have created a table in the MySQL database as shown below.
How can I read in a JSON file in Spring Boot and save the records to a database?
If you have ever had to read and write JSON data you know that this can be tricky. First, you have to read in the JSON data and mapping that data to your domain model isn't always easy. Once you have that in place you need to take that data and save it off to a database. In this tutorial, we will look at a quick and easy way to do this in Spring Boot.
Spring Boot Application
The first thing we need to do is to create a new Spring Boot application using the following dependencies.
JSON Data
The first thing we need to do is to get some dummy JSON data and one of my favorite services for doing this is JSON Placeholder. We are going to grab a list of users and save that to a file called users.json and place it inside of /src/main/resources/json/. Each JSON record for a user will look something like this.
Now that we have our list of users saved we need to model a domain after our user. We could create relationships between each of our domain models but to keep this simple I am going to store all of this data in a single user table. To accomplish this I am going to have embedded and embeddable domain models.
Spring Boot REST Application
Now that we have our domain model in place we are going to build out a REST controller that uses a service & Repository to list and save data.
The important thing about our service here is that it takes a list of users and calls our repository to save them all at once.
Read & Write JSON Data to Database
With our application in place, there is only one step left to do. To read the JSON and write it to a database we are going to use a command line runner. When we bring in the Web dependency we also get the jackson-databind dependency. This contains an Object Mapper class which allows us to easily map JSON data to our domain model.
Using that Object Mapper and our well-crafted domain model from above we have what we need to accomplish our goal. We are going to read in our users.json file and then map that data to our domain model.
If we run our application and look at the H2 Database console we can see the 10 records have been inserted.
Screencast
Conclusion
If you want to check out the source code for this project you can do so here.
Question: Are you facing any issues with JSON in your applications?