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();
}
}
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!