Week 109 — How can one parse JSON text in a Java application?

Question of the Week #109
How can one parse JSON text in a Java application?
10 Replies
CrimsonDragon1
While the JDK doesn't include a public API for parsing JSON, there are multiple available libraries for that purpose. One example of a library performing JSON parsing is json-java. This library can be added by adding the following dependency to the pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250107</version> <!-- use the latest available version here -->
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250107</version> <!-- use the latest available version here -->
</dependency>
We can then create a JSONObject from a JSON String and extract information using the corresponding methods:
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

JSONObject jsonObject = new JSONObject(json);

//we can get field of the JSONObject by calling its methods:
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
//JSONObjects can contain nested JSONObjects
JSONObject nestedJsonObject = jsonObject.getJSONObject("someNestedObject");
String nestedHello = nestedJsonObject.getString("hello");
Nested nested = new Nested(nestedHello);
Data data = new Data(id, name, nested);
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

JSONObject jsonObject = new JSONObject(json);

//we can get field of the JSONObject by calling its methods:
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
//JSONObjects can contain nested JSONObjects
JSONObject nestedJsonObject = jsonObject.getJSONObject("someNestedObject");
String nestedHello = nestedJsonObject.getString("hello");
Nested nested = new Nested(nestedHello);
Data data = new Data(id, name, nested);
CrimsonDragon1
Another library for JSON processing is Jackson which can not only parse JSON data but also automatically deserialize it to objects matching the names. To add jackson to a Maven project, the following dependency can be used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
We will then reuse the same records that are also used for demonstrating json-java:
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
To use jackson, we need to construct an ObjectMapper which can be used to convert JSON Strings to Java objects:
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper objectMapper = new ObjectMapper();
We can then convert a JSON String to a Java object using the readValue method in the ObjectMapper which accepts the JSON String and a Class object for the type we want to deserialize to:
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

Data data = objectMapper.readValue(json, Data.class);
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

Data data = objectMapper.readValue(json, Data.class);
📖 Sample answer from dan1st
CrimsonDragon1
Java itself does not include a way to parse JSON, although a person with enough knowledge can write their own parser. Still, parsing JSON in Java is easy, as there are many parser libraries available! This leads us to the first question: "which library should I use?" Currently, these are the two most popular JSON parsers: - Jackson - GSON Which one you use is only up to you. After choosing a library, the next step is to include it in our project. In this example I will use the GSON libray, as in my personal opinion it's the easiest to use. Depending on your project, including the library can be done in a few ways: - If your project is using a build system, the recommended way of including the library is to add it to the dependencies section of your build system's config file. Here are some examples: - Gradle (build.gradle):
dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.11.0'
}

dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.11.0'
}

- Maven (pom.xml):
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
<dependencies>

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

- If you are not using a build system, but are still using an IDE, you can download the .jar file manually from the Maven repository and include it in your project's dependencies using your IDE's tools. For example in Eclipse all you need to do is right-click on your project (assuming it has a Java nature), navigate to Build Path > Configure Build Path... and in the Libraries tab click on Classpath and then the Add External JARs... button. - If you are using javac to compile your code, you need to include the .jar file in the classpath, by using javac -classpath path/to/gson.jar ...
GitHub
GitHub - FasterXML/jackson-databind: General data-binding package f...
General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s) - FasterXML/jackson-databind
GitHub
GitHub - google/gson: A Java serialization/deserialization library ...
A Java serialization/deserialization library to convert Java Objects into JSON and back - google/gson
CrimsonDragon1
Now, let's assume, we have the following json:
{
"name": "John",
"surname": "Paul",
"age": 21,
"height": 173.7,
"alive": true
}
{
"name": "John",
"surname": "Paul",
"age": 21,
"height": 173.7,
"alive": true
}
stored in a file named user.json. GSON allows you to parse JSON in two main ways. You can either parse the JSON into a JsonObject/JsonElement, or, if you know the JSON's structure, you can convert it into your own object. We will go with the latter method. First, let's create a class to hold the data parsed from JSON. Our JSON has 5 fields: - name - String - surname - also a String - age - an int - height - a float - alive - a boolean With this, we can construct our class:
class User {
public String name;
public String surname;
public int age;
public float height;
public boolean alive;
}
class User {
public String name;
public String surname;
public int age;
public float height;
public boolean alive;
}
Normally you may want to make the fields private and use getters, but for this example I want to keep things as simple as possible. Now we need to actually parse the JSON. GSON allows parsing both from String and from a Reader. Since we don't have a String representation of our JSON, we need to use a FileReader. Parsing the file into a User instance is as simple as doing:
import com.google.gson.*;

public class Main {
public static void main(String[] args) {

// Open the user.json file
try (Reader reader = new FileReader("user.json")) {

// Actually parse the JSON
User user = new Gson().fromJson(reader, User.class);

// Print all of user's fields
System.out.println("Name: " + user.name);
System.out.println("Surname: " + user.surname);
System.out.println("Age: " + user.age);
System.out.println("Height (cm): " + user.height);
System.out.println("Alive: " + user.alive);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.google.gson.*;

public class Main {
public static void main(String[] args) {

// Open the user.json file
try (Reader reader = new FileReader("user.json")) {

// Actually parse the JSON
User user = new Gson().fromJson(reader, User.class);

// Print all of user's fields
System.out.println("Name: " + user.name);
System.out.println("Surname: " + user.surname);
System.out.println("Age: " + user.age);
System.out.println("Height (cm): " + user.height);
System.out.println("Alive: " + user.alive);
} catch (Exception e) {
e.printStackTrace();
}
}
}
After running the code, this should be the output:
Name: John
Surname: Paul
Age: 21
Height (cm): 173.7
Alive: true
Name: John
Surname: Paul
Age: 21
Height (cm): 173.7
Alive: true
But... What if we don't know what fields are present? Then we can't really use the method shown before. We can, however, parse our JSON into a JsonObject. You can think of JsonObject as a Map, with String keys and JsonElement values. JsonElement is a base class for all JSON elements. It can either be an instance of JsonObject, JsonArray, JsonPrimitive, or even JsonNull. Let's begin by parsing our user.json into a JsonObject. For that we'll use JsonParser:
JsonObject object;
try(Reader reader = new FileReader("user.json")) {
object = JsonParser.parseReader(reader).getAsJsonObject();
}
JsonObject object;
try(Reader reader = new FileReader("user.json")) {
object = JsonParser.parseReader(reader).getAsJsonObject();
}
CrimsonDragon1
Now, we can get json elements from the object using the get method:
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
JsonPrimitive namePrimitive = nameElement.getAsJsonPrimitive();
String name = namePrimitive.getAsString();
System.out.println(name);
}
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
JsonPrimitive namePrimitive = nameElement.getAsJsonPrimitive();
String name = namePrimitive.getAsString();
System.out.println(name);
}
This can also be simplified:
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
String name = nameElement.getAsString();
System.out.println(name);
}
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
String name = nameElement.getAsString();
System.out.println(name);
}
We can also iterate over all entries present in a JsonObject:
for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if(value.isJsonPrimitive()) {
System.out.println(key + ": " + value.getAsString());
}
}
for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if(value.isJsonPrimitive()) {
System.out.println(key + ": " + value.getAsString());
}
}
and the output will be:
name: John
surname: Paul
age: 21
height: 171.3
alive: true
name: John
surname: Paul
age: 21
height: 171.3
alive: true
⭐ Submission from java.net.defective
CrimsonDragon1
Applications should use an existing library for working with JSON. The most commonly used one is Jackson, but other popular libraries include Google's GSON and Jakarta EE's JSON-P.
GitHub - google/gson: A Java serialization/deserialization library ...
A Java serialization/deserialization library to convert Java Objects into JSON and back - google/gson
CrimsonDragon1
A quick Jackson example... Jackson exposes a couple of different "levels" of functionality. The core library provides low level parsing and generating utilities, and is the foundation that the other levels are built on:
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
JsonFactory jackson = new JsonFactory();
try (final JsonParser parser = jackson.createParser(json)) {
Employee emp = new Employee();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String keyName = parser.currentName();
if ("name".equals(keyName)) {
parser.nextToken();
emp.name = parser.getText();
} else if ("occupation".equals(keyName)) {
parser.nextToken();
emp.occupation = parser.getText();
}
}
System.out.println(emp);
}
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
JsonFactory jackson = new JsonFactory();
try (final JsonParser parser = jackson.createParser(json)) {
Employee emp = new Employee();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String keyName = parser.currentName();
if ("name".equals(keyName)) {
parser.nextToken();
emp.name = parser.getText();
} else if ("occupation".equals(keyName)) {
parser.nextToken();
emp.occupation = parser.getText();
}
}
System.out.println(emp);
}
CrimsonDragon1
Using core directly is very manual and verbose, so most applications will use the annotations and databind libraries to assist:
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(json, Employee.class);
System.out.println(emp);
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(json, Employee.class);
System.out.println(emp);
Submission from dangerously_casual
CrimsonDragon1
Important ⚠️ : The following answer is based on my knowledge and expertise using Java starting from v7 to v17 LTS for years. I have not yet fully explored the capabilities of Java 21 LTS or any subsequent versions. AFAIK, Java core do not include a built-in feature specifically designed for JSON. Alternatively there are some popular 3rd-party libraries, one of them is called Jackson, one of the most popular and powerful java libraries, it provides a set of tools to handle JSON easily and effectively. What is JSON parsing ? IMO, Parsing is a process of analyzing a string data according to a particular syntax and converting it into a structured representation like objects in Java. For JSON, parsing means interpreting a JSON text/string and converting it into a Java object. This is closely tied to serialization and deserialization. Parsing JSON Example 1. Consider the following JSON object :
{"id": 123, "name": "Jhon"}
{"id": 123, "name": "Jhon"}
2. Define a Java class model that represents the JSON :
record MyJson(long id, String name) {}
record MyJson(long id, String name) {}
3. Parse the JSON using ObjectMapper API from Jackson :
package com.myorg.myjson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import static java.lang.System.out;

public class MyJsonParser {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] arguments) {
String jsonAsString = "{ \"id\": 123, \"name\": \"Jhon\"}";
try {
MyJson json = objectMapper.readValue(jsonAsString, MyJson.class);
out.print("id : " + json.id());
out.print("name : " + json.name());
} catch (JsonProcessingException ex) {
out.print("unable to parse JSON: " + ex.getMessage());
}
}
}
package com.myorg.myjson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import static java.lang.System.out;

public class MyJsonParser {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] arguments) {
String jsonAsString = "{ \"id\": 123, \"name\": \"Jhon\"}";
try {
MyJson json = objectMapper.readValue(jsonAsString, MyJson.class);
out.print("id : " + json.id());
out.print("name : " + json.name());
} catch (JsonProcessingException ex) {
out.print("unable to parse JSON: " + ex.getMessage());
}
}
}
4. Run it :
id: 123
id: 123
Done ! 🎉
Submission from firasrg5942
CrimsonDragon1
ObjectMapper mapper = new ObjectMapper(); String jsonString = "{"name":"John", "age":30}"; JsonNode root = mapper.readTree(jsonString); Add either the jackson-databind or gson dependency to your project to make use of these librarie
Submission from pranjaldohare

Did you find this page helpful?