Skip to main content
Back to Blog

How to Format JSON in Java

Feb 01, 2026 3 min read

Java does not have a built-in JSON formatter, but the two most popular libraries, Jackson and Gson, both provide very easy ways to parse and pretty-print JSON data.

Example Code

Java
// Using Jackson (FasterXML)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class JsonFormatter {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        
        ObjectMapper mapper = new ObjectMapper();
        
        // Parse the JSON string
        Object jsonObject = mapper.readValue(jsonString, Object.class);
        
        // Pretty print it
        String formattedJson = mapper.writerWithDefaultPrettyPrinter()
                                     .writeValueAsString(jsonObject);
                                     
        System.out.println(formattedJson);
    }
}

Common Use Cases

  • Returning readable REST API JSON responses in frameworks like Spring Boot
  • Formatting and writing JSON to log files
  • Debugging deep, complex nested DTO objects

💡 Pro Tips for Java

  • Jackson writerWithDefaultPrettyPrinter() formats with spaces by default.
  • With Jackson, you can also inject ObjectWriter into Spring controllers.
  • Gson is lightweight, but Jackson offers better performance for large JSON datasets.

Format Instantly Online

Need to verify your Java DTOs or API responses? Use our secure, client-side formatter for professional JSON indentation.