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"
}
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Share image and text Twitter using your Android Application Programatically - Twitter
- How to know If you are running macOS Sequoia (15) Version? - Mac-OS-X
- Installing JD Decompiler plugin in Eclipse IDE - Eclipse
- How to SFTP to port different than 22 (SFTP Custom port) - FTP
- Python: Convert Date to DateTime - Python
- Command to check Last Login or Reboot History of Users and TTYs - Linux
- How to Show the Status Bar on Windows 11 New Notepad - Windows-11
- Python ternary operator (known as Conditional Expression) Example - Python