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
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:
We can then create a
JSONObject
from a JSON String and extract information using the corresponding methods:
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
We will then reuse the same records that are also used for demonstrating json-java:
To use jackson, we need to construct an
ObjectMapper
which can be used to convert JSON String
s to Java objects:
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:
📖 Sample answer from dan1st
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
):
- Maven (pom.xml
):
- 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
Now, let's assume, we have the following json:
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:
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:
After running the code, this should be the output:
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
:
Now, we can get json elements from the object using the
get
method:
This can also be simplified:
We can also iterate over all entries present in a JsonObject
:
and the output will be:
⭐ Submission from java.net.defective
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
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:
Using
core
directly is very manual and verbose, so most applications will use the annotations
and databind
libraries to assist:
Submission from dangerously_casual
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 :
2. Define a Java class model that represents the JSON :
3. Parse the JSON using ObjectMapper API from Jackson :
4. Run it :
Done ! 🎉
Submission from firasrg5942
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