Write JSON to file in pretty-printed Format using Java Jackson

Jackson wirte Pretty Printed Fromat Json to file
Jackson wirte Pretty Printed Fromat Json to file

If you have a use-case where you want to write a JSON string to a file and in a pretty printed format so it is easy to read, you can make use of the Java Jackson library,

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

public class JsonWriteFilePrettyPrinted {

    public static void main(String[] args) {

        try {
            Employee employee = new Employee("Jake",45,"Finance");
            ObjectMapper objectMapper = new ObjectMapper();
            File jsonFile = new File("employee.json");

        } catch (Exception e) {
Output file employee.json
  "empName" : "Jake",
  "empAge" : 45,
  "empDept" : "Finance"

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