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

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

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

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