Question
I have the following JSON text and want to parse it in Java so I can access values such as pageName, pagePic, post_id, and other fields.
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
How can I parse this JSON structure and read values from both the nested object (pageInfo) and the array of objects (posts)?
Short Answer
By the end of this page, you will understand how JSON is structured, how to parse JSON in Java, and how to extract values from nested objects and arrays. You will also see practical examples using a common Java JSON library and learn the mistakes beginners often make.
Concept
JSON stands for JavaScript Object Notation. It is a text format used to store and exchange structured data.
In Java, JSON is not built into the language in the same way as primitive types or collections, so you usually use a library to parse it. Common choices include:
org.json- Gson
- Jackson
The core idea is simple:
- A JSON object maps to key-value pairs.
- A JSON array holds a list of values.
- Values can be strings, numbers, booleans, arrays, objects, or
null.
In your JSON:
pageInfois a nested object.postsis an array.- The first item inside
postsis another object.
This matters in real programming because APIs often return JSON. If your Java application consumes web services, reads configuration files, or processes structured data, you need to know how to:
- parse JSON text
- navigate nested structures
- safely extract values
- loop through arrays of objects
A beginner-friendly way to learn this is to first parse JSON into an object model, then access fields by key.
Mental Model
Think of JSON like a set of boxes and lists:
- A JSON object is like a labeled storage cabinet.
- Each label is a key like
pageName. - Each drawer contains a value.
- Each label is a key like
- A JSON array is like a numbered list.
- You access items by position: first, second, third.
For your JSON:
- The outer object is the main cabinet.
- Inside it,
pageInfois a smaller cabinet. postsis a list.- Each item in
postsis another cabinet containing post details.
So parsing JSON in Java means:
- Open the main cabinet.
- Find the
pageInfodrawer and read values from it. - Find the
postslist. - Open the first post and read fields like
post_id.
If you remember object = keys and array = indexes, JSON becomes much easier to navigate.
Syntax and Examples
A common beginner-friendly approach in Java is to use the org.json library.
Core syntax
JSONObject root = new JSONObject(jsonText);
JSONObject pageInfo = root.getJSONObject("pageInfo");
String pageName = pageInfo.getString("pageName");
JSONArray posts = root.getJSONArray("posts");
JSONObject firstPost = posts.getJSONObject(0);
String postId = firstPost.getString("post_id");
Full example
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String ;
(jsonText);
root.getJSONObject();
pageInfo.getString();
pageInfo.getString();
root.getJSONArray();
posts.getJSONObject();
firstPost.getString();
firstPost.getString();
firstPost.getString();
System.out.println( + pageName);
System.out.println( + pagePic);
System.out.println( + postId);
System.out.println( + actorId);
System.out.println( + message);
}
}
Step by Step Execution
Consider this shorter example:
String json = """
{
"pageInfo": {
"pageName": "abc"
},
"posts": [
{
"post_id": "123",
"message": "Hello"
}
]
}
""";
JSONObject root = new JSONObject(json);
JSONObject pageInfo = root.getJSONObject("pageInfo");
String pageName = pageInfo.getString("pageName");
JSONArray posts = root.getJSONArray("posts");
JSONObject firstPost = posts.getJSONObject(0);
String postId = firstPost.getString("post_id");
Step by step
-
String json = ...- Stores the raw JSON text.
-
JSONObject root = new JSONObject(json);- Parses the text into a Java object representing the outer JSON object.
Real World Use Cases
Parsing JSON in Java is used in many common situations:
API responses
A Java application may call a REST API and receive JSON like:
- user profiles
- blog posts
- product data
- payment results
You parse the response to extract fields your app needs.
Configuration files
Some Java programs load JSON configuration such as:
- app settings
- feature flags
- environment-specific values
Data import scripts
You may read JSON files and convert them into:
- database records
- CSV reports
- Java objects
Logging and event processing
Systems often store events as JSON, such as:
- audit logs
- analytics events
- webhook payloads
Mobile and web backends
Java backends frequently receive JSON from clients and send JSON back in responses.
Your example is similar to data returned by a social or content API, where one object contains page metadata and a list of posts.
Real Codebase Usage
In real projects, developers usually do more than just call getString() repeatedly.
Common patterns
Validation before reading
Developers often check whether keys exist before accessing them.
if (root.has("pageInfo")) {
JSONObject pageInfo = root.getJSONObject("pageInfo");
}
Safer optional access
Some libraries provide optional methods such as optString() to avoid exceptions when a key is missing.
String pageName = pageInfo.optString("pageName", "");
Looping through arrays
Real API responses often contain many items.
JSONArray posts = root.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject post posts.getJSONObject(i);
System.out.println(post.getString());
}
Common Mistakes
1. Treating an array like an object
Broken code:
JSONObject posts = root.getJSONObject("posts");
Why it is wrong:
postsis a JSON array, not an object.
Correct code:
JSONArray posts = root.getJSONArray("posts");
2. Forgetting to access an array item by index
Broken code:
String postId = posts.getString("post_id");
Why it is wrong:
- Arrays use numeric indexes.
- You must first get an object from the array.
Correct code:
JSONObject firstPost = posts.getJSONObject(0);
String postId = firstPost.getString("post_id");
Comparisons
Manual JSON access vs mapping to Java classes
| Approach | How it works | Best for | Pros | Cons |
|---|---|---|---|---|
Manual parsing with JSONObject | Access keys and arrays directly | Small JSON examples, quick scripts, learning | Simple to start, easy to inspect structure | Becomes repetitive for large JSON |
| Mapping with Gson/Jackson | Convert JSON into Java classes | Larger apps, structured API models | Cleaner code, easier to maintain | Requires defining classes |
JSON object vs JSON array
| JSON type | Example | Access style |
|---|---|---|
| Object | {"pageName":"abc"} |
Cheat Sheet
JSON parsing basics in Java
JSONObject root = new JSONObject(jsonText);
Read a nested object
JSONObject pageInfo = root.getJSONObject("pageInfo");
String pageName = pageInfo.getString("pageName");
String pagePic = pageInfo.getString("pagePic");
Read an array
JSONArray posts = root.getJSONArray("posts");
Read the first object in an array
JSONObject firstPost = posts.getJSONObject(0);
String postId = firstPost.getString("post_id");
Loop through an array
FAQ
How do I parse JSON in Java?
Use a JSON library such as org.json, Gson, or Jackson. Parse the JSON string into an object, then access nested objects and arrays.
How do I get a value from a nested JSON object in Java?
First get the nested object, then read its field:
JSONObject pageInfo = root.getJSONObject("pageInfo");
String pageName = pageInfo.getString("pageName");
How do I read a JSON array in Java?
Use getJSONArray(), then access items by index:
JSONArray posts = root.getJSONArray("posts");
JSONObject firstPost = posts.getJSONObject(0);
What happens if a JSON key does not exist?
Methods like getString() usually throw an exception. Safer methods like optString() return a default value instead.
Which Java JSON library should beginners use?
org.json is easy for learning manual parsing. Gson and Jackson are often better for larger applications.
Mini Project
Description
Build a small Java program that parses a JSON response representing a page and its posts. This project demonstrates how to read nested objects, loop through arrays, and safely print extracted values from structured JSON data.
Goal
Create a Java program that reads page information and prints every post's main details from a JSON string.
Requirements
[
"Parse the JSON string into a root JSON object.",
"Read and print pageName and pagePic from the pageInfo object.",
"Read the posts array and loop through every post.",
"Print each post's post_id, nameOfPersonWhoPosted, and message.",
"Handle the case where the posts array is empty."
]
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.