How to Parse JSON in Java
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);