How to Parse JSON in Java

← All guides

Java has no built-in JSON parser, but Jackson is the de-facto standard. Use ObjectMapper to bind JSON to POJOs or read a JsonNode tree.

Deserialize to a POJO with Jackson

ObjectMapper.readValue maps JSON to a plain Java object based on field names.

java
record User(String name, List<String> roles) {}

ObjectMapper mapper = new ObjectMapper();
User u = mapper.readValue(text, User.class);
System.out.println(u.name());

Read a JSON tree

When you don't have a class, read a JsonNode and navigate it.

java
JsonNode root = mapper.readTree(text);
String name = root.get("name").asText();
String first = root.get("roles").get(0).asText();

Serialize and pretty-print

writeValueAsString serializes; the default pretty printer indents the output.

java
String json = mapper.writeValueAsString(u);
String pretty = mapper.writerWithDefaultPrettyPrinter()
                      .writeValueAsString(u);

Frequently Asked Questions

Both are solid. Jackson is more feature-rich and common in Spring; Gson is lightweight and simple. This guide uses Jackson.

Use the JSON to Java tool to produce POJOs (Jackson-annotated or Lombok @Data) from a sample document.

Configure the mapper with FAIL_ON_UNKNOWN_PROPERTIES = false, or annotate the class with @JsonIgnoreProperties(ignoreUnknown = true).

Related Tools