How to Parse JSON in Java: Jackson and Gson Guide
Parse JSON in Java with Jackson and Gson: ObjectMapper readValue, the JsonNode tree model, reading files and arrays, writing JSON back, and handling common errors and unknown fields.
Java has no built-in JSON parser, so every Java project picks a library — almost always Jackson or Gson. Both turn JSON text into Java objects and back, but they differ in defaults, performance, and API style. This guide shows how to parse JSON in Java the practical way: mapping JSON to POJOs, walking it as a tree when you do not have a class, reading from files and HTTP responses, and handling the errors you will actually hit.
Jackson: the de facto standard
Jackson is the most widely used JSON library in the Java ecosystem, and its ObjectMapper class is the simplest entry point. Create one ObjectMapper and reuse it — the first time it sees a type it scans the getters and fields and caches an internal model, so reusing the instance is both faster and thread-safe for reads.
The core call is readValue: ObjectMapper mapper = new ObjectMapper(); Car car = mapper.readValue(json, Car.class); turns a JSON string into a typed Car object. The same method overloads accept an InputStream, a Reader, a File, or a byte array, so you can read straight from disk or an HTTP response body.
Mapping JSON to a POJO
The typed approach binds JSON fields to a class whose property names match the JSON keys. Jackson matches by getter, setter, or field name, and you can override a name with the @JsonProperty annotation when the JSON key differs from Java conventions. This is the cleanest pattern for well-known, stable payloads because it gives you compile-time types and IDE autocomplete.
If you only have a JSON sample and no class yet, generate one: a JSON to Java tool produces the POJO fields for you so you do not hand-write boilerplate for a large response.
// json holds: { "brand": "Mercedes", "doors": 5 }
ObjectMapper mapper = new ObjectMapper();
Car car = mapper.readValue(json, Car.class);The tree model: JsonNode
When the structure is dynamic or you only need a few fields, parse JSON into a tree instead of a class. mapper.readTree(json) returns a JsonNode you can navigate: node.get("name").asText() reads a string, and node.get("age").asInt() reads a number. For arrays, loop over the node, which is iterable, and extract each element.
The tree model trades type safety for flexibility — perfect for partial reads, unknown shapes, or quickly probing an API during development.
JsonNode root = mapper.readTree(json);
String brand = root.get("brand").asText();
int doors = root.get("doors").asInt();Writing JSON back out
Serialization is the mirror image: mapper.writeValueAsString(car) returns a JSON string, and writeValue(file, car) writes straight to a file. For readable output, enable pretty printing with mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj). Jackson handles nested objects, collections, and maps automatically.
Gson: Google's lightweight alternative
Gson offers a similarly clean API: new Gson().fromJson(json, Car.class) parses, and gson.toJson(car) serializes. It has no required annotations for basic use and a small footprint, which makes it popular on Android and in simpler services. Jackson tends to win on raw performance and ecosystem breadth (streaming, modules, data formats), while Gson wins on simplicity and zero-config defaults.
Handling errors and unknown fields
Invalid JSON throws a JsonProcessingException (Jackson) or JsonSyntaxException (Gson); wrap parsing in try/catch and surface the message, which points at the problem. By default, Jackson fails when the JSON contains a property your class does not declare. To tolerate extra fields from an evolving API, configure the mapper to ignore unknown properties (FAIL_ON_UNKNOWN_PROPERTIES set to false), or annotate the class with @JsonIgnoreProperties(ignoreUnknown = true).
mapper.configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or annotate the class:
// @JsonIgnoreProperties(ignoreUnknown = true)Validate before you parse
When a payload will not bind, confirm the JSON itself is well-formed before debugging your classes. Paste it into a JSON validator to get the exact line and column of any syntax error, or a formatter to inspect the structure. Catching a malformed response in the data is faster than chasing a JsonProcessingException stack trace.
Frequently asked questions
Should I use Jackson or Gson?
Use Jackson for most server-side Java — it is the ecosystem standard with the best performance, streaming support, and module coverage. Choose Gson for simpler needs, smaller dependencies, or Android, where its zero-config API is convenient. Both parse and serialize JSON cleanly.
How do I parse a JSON string into a Java object?
With Jackson: ObjectMapper mapper = new ObjectMapper(); MyClass obj = mapper.readValue(jsonString, MyClass.class). With Gson: MyClass obj = new Gson().fromJson(jsonString, MyClass.class). Both bind JSON keys to the matching fields of your class.
How do I parse JSON without a class in Java?
Use Jackson's tree model: JsonNode node = mapper.readTree(json), then navigate with node.get("key").asText() or asInt(). This avoids defining a POJO and is ideal for dynamic or partial reads.
How do I ignore unknown JSON fields in Jackson?
Either configure the mapper with FAIL_ON_UNKNOWN_PROPERTIES set to false, or annotate the target class with @JsonIgnoreProperties(ignoreUnknown = true). This lets your code tolerate extra fields added by an evolving API.
Is ObjectMapper thread-safe?
Yes for read and configuration-stable use. Create one ObjectMapper, configure it up front, and reuse it across threads. Reconfiguring it concurrently is not safe, but sharing a configured instance for reads and writes is the recommended pattern.
Related tools
Try these tools
JSON to Java Class Generator
Generate Java classes with Jackson annotations from JSON samples.
JSON Validator
Validate JSON instantly with precise, human-readable error messages and line numbers.
JSON Formatter & Beautifier
Format, prettify, and beautify messy JSON with configurable indentation and key sorting.
JSON Repair & Fix
Fix invalid JSON: trailing commas, quotes, unquoted keys, and LLM markdown fences.