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