How to Parse a JSON String in Java (Jackson, Gson & org.json)
Java does not include JSON parsing in its standard library, so the first question every Java developer asks is: which library do I use, and how? Whether you need to parse a JSON string into an object, read a JSON file, or turn a Java object back into JSON, the answer comes down to three popular libraries - Jackson, Gson, and org.json. This guide shows you how to parse a JSON string in Java with each one, when to choose which, and the common pitfalls that cause the dreaded parsing exceptions. Every example is copy-paste ready.
Parsing JSON in Java: Why You Need a Library
Unlike Python or JavaScript, Java has no built-in JSON support in its core libraries (the JDK). To parse a JSON string in Java, you add one of three widely-used third-party libraries to your project. Each takes a JSON string and converts it into something usable - either a structured tree you navigate manually, or a Java object whose fields are populated automatically (a process called deserialization).
The three standard choices are Jackson (the most popular, used by Spring Boot by default), Gson (Google's library, simple and lightweight), and org.json (a minimal, no-frills option). Jackson and Gson both support mapping JSON directly onto your Java classes, which is the cleanest approach for structured data. org.json is best for quick, manual navigation of JSON without defining classes. You add the library as a Maven or Gradle dependency, and then parsing is a one or two line call.
How to Parse a JSON String in Java - Step by Step
Method 1 - Jackson (most popular)
Add the Jackson dependency to your project, then use ObjectMapper. To parse a JSON string into a Java object (POJO):
Here User is a simple Java class with fields matching the JSON keys. Jackson maps the JSON onto the object automatically. To parse into a generic tree when you do not have a class, use JsonNode:
Method 2 - Gson (simple and lightweight)
Google's Gson library uses similar syntax. To parse a JSON string into an object:
Gson is known for its clean API and is a great choice when you want minimal configuration.
Method 3 - org.json (minimal, no classes needed)
For quick parsing without defining a class, org.json lets you navigate the JSON directly:
→ Before parsing, make sure your JSON string is valid - a single misplaced bracket causes a parsing exception. Check it with our free JSON Formatter and Validator at GlobalUtilityHub - no sign-up needed.
Converting a Java object back to a JSON string
All three libraries also serialize objects to JSON. With Jackson: String json = mapper.writeValueAsString(user); With Gson: String json = gson.toJson(user);
Worked Example: Parsing JSON into a Java Object
Suppose you receive this JSON string from an API:
First, define a matching Java class:
Then parse it with Jackson:
Jackson matched each JSON key to the corresponding field automatically. The field names in your class must match the JSON keys (or you annotate them with @JsonProperty to map differing names).
Java JSON Libraries Compared
Choosing the right library depends on your project. This table summarizes the trade-offs.
| Library | Maven artifact | Best for | Maps to classes? | Notes |
|---|---|---|---|---|
| Jackson | jackson-databind | Most projects, Spring Boot | Yes | Industry standard, feature-rich |
| Gson | gson | Android, lightweight apps | Yes | Simple API, Google-maintained |
| org.json | json | Quick manual parsing | No | Minimal, no POJO needed |
Common Mistakes to Avoid
@JsonProperty("json_key") in Jackson or @SerializedName("json_key") in Gson to map them."{"name":"Alice"}". Forgetting this causes a compile error. In Java 15+, you can use text blocks (triple quotes) to avoid the escaping.readValue throws JsonProcessingException, a checked exception you must catch or declare. Wrap parsing in a try/catch block or add throws to your method signature, or your code will not compile.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) to ignore unexpected fields - essential when consuming external APIs that may add fields over time.Parsing Nested JSON and Arrays into Java Collections
Most real JSON has nested objects and arrays, and both Jackson and Gson handle them cleanly once you model your classes correctly. The key principle: your Java class structure must mirror the JSON structure.
Suppose you have JSON with a nested object and an array:
You model this with a matching class hierarchy - an Address class for the nested object and a List for the array:
Then parsing is the same single call - Jackson populates the nested Address object and the roles list automatically:
When the top-level JSON is an array rather than a single object, use a TypeReference (Jackson) or TypeToken (Gson) to preserve the generic type, since Java erases generics at runtime:
Without the TypeReference, Java cannot tell the library what type the list should contain, and you would get a list of generic maps instead of typed User objects.
Performance Tips and Best Practices
Once you are parsing JSON regularly in a Java application, a few practices keep your code fast and maintainable.
ObjectMapper for every parse is wasteful - it is an expensive object to instantiate. Create one instance and reuse it across your application. The ObjectMapper is thread-safe once configured, so a single shared instance (often a static field or a Spring bean) is the recommended pattern.FAIL_ON_UNKNOWN_PROPERTIES when you create the mapper, not on every call. This keeps configuration centralized and avoids repeated setup.JsonParser) reads token by token, letting you process arbitrarily large files with constant memory. It is more verbose but essential for multi-gigabyte data.JsonNode tree with string keys that can fail silently at runtime.For server applications using Spring Boot, Jackson is already configured and wired in - you rarely need to create an ObjectMapper manually, as the framework handles JSON parsing for request and response bodies automatically.
Adding the Library: Maven and Gradle Setup
Because JSON parsing in Java requires a third-party library, the first practical step is adding it to your build file. Here is exactly what to add for each of the three libraries, in both Maven and Gradle.
Jackson
For Maven, add this to your pom.xml dependencies (check for the latest 2.x version):
For Gradle, add this to build.gradle:
Gson
Maven:
Gradle:
org.json
Maven:
After adding the dependency, refresh your project (Maven's mvn install or letting your IDE re-import) so the library downloads. If you use Spring Boot, Jackson is already included transitively through spring-boot-starter-web - you do not need to add it separately, which is one more reason Jackson is the default choice for server-side Java. Always check Maven Central for the current version number, since libraries are updated regularly with bug fixes and security patches.
Frequently Asked Questions
How do I parse a JSON string in Java?
Java has no built-in JSON parser, so you use a library. The most popular is Jackson: create an ObjectMapper and call mapper.readValue(jsonString, YourClass.class) to parse into an object, or mapper.readTree(jsonString) for a navigable tree. Alternatives are Gson (gson.fromJson()) and org.json (new JSONObject(jsonString)). Add the library as a dependency first.
How do I parse a JSON string into a Java object?
Define a Java class (POJO) with fields matching the JSON keys, then deserialize. With Jackson: User user = mapper.readValue(jsonString, User.class). With Gson: User user = gson.fromJson(jsonString, User.class). The library populates the fields automatically. Field names must match JSON keys (or use annotations), and include a no-argument constructor.
How do I convert a Java object to a JSON string?
Use your library's serialization method. Jackson: String json = mapper.writeValueAsString(yourObject). Gson: String json = gson.toJson(yourObject). For pretty-printed output in Jackson use mapper.writerWithDefaultPrettyPrinter(); in Gson build it with new GsonBuilder().setPrettyPrinting().create().
Which JSON library is best for Java?
Jackson is the most widely used and the default in Spring Boot, making it the safest choice for most server-side projects. Gson is simpler and popular in Android. org.json is minimal and good for quick parsing without classes. For new projects, Jackson is generally recommended; choose Gson for lightweight needs or org.json for quick value reads.
How do I read a JSON file into a string in Java?
Read the file into a string then parse, or parse the file directly. In Java 11+: String content = Files.readString(Path.of("data.json")); (Java 11+), then pass content to your parser. Alternatively, Jackson and Gson read directly from a File: mapper.readValue(new File("data.json"), User.class), skipping the manual string step.
How do I parse a JSON array in Java?
Deserialize into a List. With Jackson use a TypeReference: List<User> users = mapper.readValue(jsonString, new TypeReference<List<User>>(){}). With Gson use TypeToken: Type listType = new TypeToken<List<User>>(){}.getType(); List<User> users = gson.fromJson(jsonString, listType). These tell the library the generic type.
Why is my parsed Java object null or empty?
The most common cause is a mismatch between class field names and JSON keys - if they do not match, fields stay at default values. Check that names align, accounting for case. Use @JsonProperty (Jackson) or @SerializedName (Gson) to map differing names. Ensure proper getters and setters and a no-argument constructor.
How do I handle unknown or extra JSON fields in Java?
By default Jackson throws an exception on fields your class does not define. To ignore them, configure mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) or annotate the class with @JsonIgnoreProperties(ignoreUnknown = true). This matters when consuming third-party APIs that may add fields. Gson ignores unknown fields by default.
The Bottom Line
Parsing a JSON string in Java requires a library, and the three standards are Jackson (the default choice for most projects), Gson (simple and Android-friendly), and org.json (minimal, no classes needed). Define a matching Java class, mind the field-name alignment, handle the checked exceptions, and configure unknown-field handling for external APIs - and JSON parsing in Java becomes routine.
A single misplaced bracket will throw a parsing exception, so validate your JSON first. Our JSON Formatter and Validator catches errors in under 30 seconds - try it free at /dev-tools/json-formatter/.
Use our free JSON Formatter to apply what you have learned.
Open JSON Formatter →