Save Java Object as JSON file using Jackson Library

In this example, we will take a look at how we can save a Java Object as a JSON file using the Jackson Library ObjectMapper class and Java File class from package,

import com.fasterxml.jackson.databind.ObjectMapper;


public class SavaJavaObjectAsJson {

    public static void main(String[] args) {

        Album album = new Album();
        album.setArtistName("Michael Jackson");

        String[] songs = new String[9];
        songs[0] = "Wanna Be Startin Somethin";
        songs[1] = "Baby Be Mine";
        songs[2] = "The Girl Is Mine";
        songs[3] = "Thriller";
        songs[4] = "Beat it";
        songs[5] = "Billie Jean";
        songs[6] = "Human Nature";
        songs[7] = "P.Y.T. (Pretty Young Thing)";
        songs[8] = "The Lady in My Life";

        try {
            String jsonFileName = "album.json";
            File jsonFile = new File(jsonFileName);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(jsonFile, album);
        } catch (IOException e) {
        } catch (Exception e) {
Output - Java Object to JSON File
Output - Java Object to JSON File

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.