
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"
}
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!