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 java.io package,

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;

public class SavaJavaObjectAsJson {

    public static void main(String[] args) {

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

        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";
        album.setSongsList(songs);
        album.setReleaseYear(1982);

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

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap