Calculators Converters Generators Developer Tools Finance Tools Writing Tools SEO Tools Image Tools Network Tools Productivity Tools Social Media Tools
Blog About Contact
Dev ToolsJune 3, 20267 min read

How to Parse a JSON String in Java (Jackson, Gson & org.json)

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):

import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(jsonString, User.class); System.out.println(user.getName());

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:

JsonNode node = mapper.readTree(jsonString); String name = node.get("name").asText();

Method 2 - Gson (simple and lightweight)

Google's Gson library uses similar syntax. To parse a JSON string into an object:

import com.google.gson.Gson; Gson gson = new Gson(); User user = gson.fromJson(jsonString, User.class); System.out.println(user.getName());

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:

import org.json.JSONObject; JSONObject obj = new JSONObject(jsonString); String name = obj.getString("name"); int age = obj.getInt("age");

→ 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:

String jsonString = "{"name":"Alice","age":30,"active":true}";

First, define a matching Java class:

public class User { private String name; private int age; private boolean active; // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }

Then parse it with Jackson:

ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(jsonString, User.class); System.out.println(user.getName()); // Alice System.out.println(user.getAge()); // 30 System.out.println(user.isActive()); // true

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.

LibraryMaven artifactBest forMaps to classes?Notes
Jacksonjackson-databindMost projects, Spring BootYesIndustry standard, feature-rich
GsongsonAndroid, lightweight appsYesSimple API, Google-maintained
org.jsonjsonQuick manual parsingNoMinimal, no POJO needed

Common Mistakes to Avoid

Field names not matching JSON keys. With Jackson and Gson, your Java class field names must match the JSON keys exactly, or the fields stay null. When keys differ (for example, snake_case JSON with camelCase Java fields), use @JsonProperty("json_key") in Jackson or @SerializedName("json_key") in Gson to map them.
Forgetting to escape quotes in the string literal. When you hard-code a JSON string in Java, every double quote inside it must be escaped with a backslash: "{"name":"Alice"}". Forgetting this causes a compile error. In Java 15+, you can use text blocks (triple quotes) to avoid the escaping.
Not handling the checked exceptions. Jackson's 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.
Missing fields or extra fields causing failures. By default, Jackson throws an exception if the JSON contains a field not present in your class. Configure mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) to ignore unexpected fields - essential when consuming external APIs that may add fields over time.
Missing a no-argument constructor. Jackson and Gson need a default (no-argument) constructor to instantiate your class during deserialization. If you only define a constructor with parameters, parsing fails. Add an explicit no-arg constructor, or rely on the implicit one by not defining any constructors.

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:

{ "name": "Alice", "address": {"city": "Mumbai", "zip": "400001"}, "roles": ["editor", "admin"] }

You model this with a matching class hierarchy - an Address class for the nested object and a List for the array:

public class User { private String name; private Address address; private List<String> roles; // getters and setters } public class Address { private String city; private String zip; // getters and setters }

Then parsing is the same single call - Jackson populates the nested Address object and the roles list automatically:

User user = mapper.readValue(jsonString, User.class); System.out.println(user.getAddress().getCity()); // Mumbai System.out.println(user.getRoles().get(0)); // editor

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:

List<User> users = mapper.readValue( jsonArrayString, new TypeReference<List<User>>() {} );

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.

Reuse a single ObjectMapper. Creating a new Jackson 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.
Configure once, parse many times. Set options like FAIL_ON_UNKNOWN_PROPERTIES when you create the mapper, not on every call. This keeps configuration centralized and avoids repeated setup.
Use streaming for very large JSON. For huge files, loading everything into objects can exhaust memory. Jackson's streaming API (JsonParser) reads token by token, letting you process arbitrarily large files with constant memory. It is more verbose but essential for multi-gigabyte data.
Prefer typed objects over generic trees. Parsing into a defined class (POJO) is cleaner, safer, and catches structural mistakes at compile time, compared to navigating a JsonNode tree with string keys that can fail silently at runtime.
Validate untrusted input. When parsing JSON from external sources, always wrap the call in proper exception handling and consider size limits. Malformed or maliciously large JSON can crash a service that assumes well-formed input.

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):

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.17.0</version> </dependency>

For Gradle, add this to build.gradle:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0'

Gson

Maven:

<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.11.0</version> </dependency>

Gradle:

implementation 'com.google.code.gson:gson:2.11.0'

org.json

Maven:

<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency>

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&lt;User&gt; users = mapper.readValue(jsonString, new TypeReference&lt;List&lt;User&gt;&gt;(){}). With Gson use TypeToken: Type listType = new TypeToken&lt;List&lt;User&gt;&gt;(){}.getType(); List&lt;User&gt; 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/.

✍️ Written by <em>Written by the GlobalUtilityHub Editorial Team|📅 Last reviewed: June 2026|Fact-checked for accuracy</em>
Ready to try it yourself?

Use our free JSON Formatter to apply what you have learned.

Open JSON Formatter

Frequently Asked Questions

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.
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.
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().
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.
Read the file into a string then parse, or parse the file directly. In Java 11+: String content = Files.readString(Path.of('data.json')), 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.
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.
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.
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.