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,

Example:
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");
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile,employee);

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


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements