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


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

Advertisements

Advertisements
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.