Convert JSON to CSV using Jackson library

Jackson library makes it possible for us to convert data in JSON form to different data formats and vice versa. In this tutorial, I will show you how to convert data from JSON to CSV!

First, I will create a new Maven project:

with Jackson Dataformat CSV dependency as follows:

As an example, I will convert the following JSON string to a CSV file:

To start, I will create a new Application class with the main() method as follows:

First, you can use the readTree() method of Jackson’s ObjectMapper object to read the JSON content that you need to convert.

There are many overload readTree() methods to help you do this:

You can read JSON content from file, from string, from byte,… Depending on your need, please use overload methods of readTree() for reasonable. Here, I will save the above JSON content into the data.json file in the src/main/resources directory for an example:

This JSON content will be saved to the JsonNode object as you can see!

Next, we will use the CsvSchema Builder object to define the columns of the CSV file.

For my example, the code would look like this:

The above code is that we are getting all the keys in the JSON data, including name, code, date, gotMarried in our example, to define it as a column in the CSV file.

You can also specify which data, corresponding to which key in the JSON data, is converted to a CSV file by defining the CsvSchema Builder as follows:

With this code, my example only has the data of the column name, code and date converted. I will use this code in this tutorial as an example.

After you have the CsvSchema Builder, you can get the CsvSchema object as follows:

Now we can use CsvMapper to convert JSON data to CSV data:

Because I am defining the columns manually, there will be columns that CsvMapper is not aware of when doing the conversion. Therefore, I need to configure it to ignore those columns.

In this example, I save the output file data.csv in the directory src/main/resources.

The entire code of the example is as follows:

The output when running the program is as follows:

Jackson will not work with nested JSON data types.

For example, if you have the following JSON string:

then when you code, you need to manually define the names of the columns to remove these nested JSON guys!

Add Comment