DevToolsForYou

JSON Formatter, Minifier, and Validator in Java — Code Examples

JSON Formatter, Minifier, and Validator in JavaUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

Java has no built-in JSON library. Jackson (ObjectMapper) is the standard choice; Gson is also popular.

Jackson (most common)
// Maven: com.fasterxml.jackson.core:jackson-databind
import com.fasterxml.jackson.databind.*;

public class JsonExample {
    record User(String name, int age) {}

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Parse JSON → object
        String json = "{"name":"Alice","age":30}";
        User user = mapper.readValue(json, User.class);
        System.out.println(user.name()); // Alice

        // Serialize object → JSON
        String out = mapper.writeValueAsString(user);
        System.out.println(out); // {"name":"Alice","age":30}

        // Pretty-print
        String pretty = mapper.writerWithDefaultPrettyPrinter()
                              .writeValueAsString(user);
        System.out.println(pretty);

        // Parse into Map (unknown structure)
        Map<String, Object> map = mapper.readValue(json, Map.class);
        System.out.println(map.get("name")); // Alice
    }
}
Notes & gotchas
  • ObjectMapper is thread-safe and expensive to create — make it a singleton or Spring bean.
  • Use @JsonProperty on fields to map different JSON key names to Java field names.
  • Enable mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) to ignore extra JSON fields.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages