eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

JSON (JavaScript Object Notation) is a lightweight data-interchange format, and we most commonly use it for client-server communication. Furthermore, it’s both easy to read/write and language-independent. A JSON value can be another JSON object, array, number, string, boolean (true/false), or null.

In this tutorial, we’ll see how to create, manipulate, and parse JSON using one of the available JSON processing libraries in Java – the JSON-Java library, also known as org.json.

2. Prerequisite

First, let’s add the following dependency in our pom.xml:

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

We can get the latest version from the Maven Central Repository.

However, let’s not include the dependency explicitly when using the Android SDK, since it already includes the package.

3. JSON in Java [package org.json]

We use classes from the JSON-Java library to parse and manipulate JSON in Java. We also know this library as org.json. However, we should not confuse it with Google’s org.json.simple library.

Furthermore, this library can also convert between JSON, XML, HTTP Headers, Cookies, Comma Delimited List, or Text, etc.

In this tutorial, we’ll have a look at the following classes:

  1. JSONObject – similar to Java’s native Map-like object, which stores unordered key-value pairs
  2. JSONArray – an ordered sequence of values similar to Java’s native Vector implementation
  3. JSONTokener – a tool that breaks a piece of text into a series of tokens that can be used by JSONObject or JSONArray to parse JSON strings
  4. CDL – a tool that provides methods to convert comma-delimited text into a JSONArray and vice versa
  5. Cookie – converts from JSON String to cookies and vice versa
  6. HTTP – used to convert from JSON String to HTTP headers and vice versa
  7. JSONException – a standard exception thrown by this library

4. JSONObject

A JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations.

  • Keys are unique Strings that cannot be null.
  • Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject.NULL object.
  • A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and pairs separated by a comma.
  • It has several constructors with which to construct a JSONObject.

It also supports the following main methods:

  1. get(String key) – gets the object associated with the supplied key, throws JSONException if the key is not found
  2. opt(String key) – gets the object associated with the supplied key, null otherwise
  3. put(String key, Object value) – inserts or replaces a key-value pair in current JSONObject.

The put() method is an overloaded method that accepts a key of type String and multiple types for the value.

For the complete list of methods supported by JSONObject, visit the official documentation.

Let’s now discuss some of the main operations supported by this class.

4.1. Creating JSON Directly From JSONObject

JSONObject exposes an API similar to Java’s Map interface.

We can use the put() method and supply the key and value as arguments:

JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");

Now our JSONObject would look like this:

{"city":"chicago","name":"jon doe","age":"22"}

The JSONObject.put() method provides seven different overloaded signatures. While the key can only be a unique, non-null String, the value can be anything.

4.2. Creating JSON From Map

Instead of directly putting key and values in a JSONObject, we can construct a custom Map and then pass it as an argument to JSONObject‘s constructor.

This example will produce same results as above:

Map<String, String> map = new HashMap<>();
map.put("name", "jon doe");
map.put("age", "22");
map.put("city", "chicago");
JSONObject jo = new JSONObject(map);

4.3. Creating JSONObject From JSON String

To parse a JSON String to a JSONObject, we can just pass the String to the constructor. Let’s remember to escape the double quotes in the JSON string.

This example will produce the same results as above:

JSONObject jo = new JSONObject(
  "{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}"
);

The passed String argument must be a valid JSON; otherwise, this constructor may throw a JSONException.

4.4. Parsing JSON Values From a JSON String

Once we have constructed a JSONObject instance from a String, we can use the corresponding get method to get the value of each property.

Furthermore, we can create a JSONObject for a nested property whose value is JSON. We can repeat this as many times as needed to obtain nested JSON values. Let’s demonstrate with an example:

@Test
void givenJSON_whenParsed_thenCorrectValueReturned() {
    String jsonString = """
                        {
                            "type": "Feature", 
                            "geometry": "Point",
                            "properties": {
                                              "isValid": true, 
                                              "name": "Sample Point"
                                          }
                        }
                        """;
    JSONObject jsonObject = new JSONObject(jsonString);
    String type = jsonObject.getString("type");
    String geometry = jsonObject.getString("geometry");
    JSONObject properties = jsonObject.getJSONObject("properties");
    boolean isValid = properties.getBoolean("isValid");
    assertEquals(type,"Feature");
    assertEquals(geometry,"Point");
    assertTrue(isValid);
}

4.5. Serialize Java Object to JSON

One of JSONObject’s constructors takes a POJO as its argument. In the example below, the package uses the getters from the DemoBean class and creates an appropriate JSONObject for the same.

To get a JSONObject from a Java Object, we’ll have to use a class that is a valid Java Bean:

DemoBean demo = new DemoBean();
demo.setId(1);
demo.setName("lorem ipsum");
demo.setActive(true);

JSONObject jo = new JSONObject(demo);

And here’s the JSONObject jo:

{
    "name":"lorem ipsum",
    "active":true,
    "id":1
}

Although we have a way to serialize a Java object to JSON string, there is no way to convert it back using this library. If we want that kind of flexibility, we can switch to other libraries such as Jackson.

5. JSONArray

A JSONArray is an ordered collection of values, resembling Java’s native Vector implementation:

  • Values can be anything from a Number, String, Boolean, JSONArray, or JSONObject to even a JSONObject.NULL object
  • It’s represented by a String wrapped within square brackets and consists of a collection of values separated by commas
  • Like JSONObject, it has a constructor that accepts a source String and parses it to construct a JSONArray

These are the primary methods of the JSONArray class:

  1. get(int index) – returns the value at the specified index (between 0 and total length – 1), otherwise throws a JSONException
  2. opt(int index) – returns the value associated with an index (between 0 and total length – 1). If there’s no value at that index, then a null is returned.
  3. put(Object value) – append an object value to this JSONArray. This method is overloaded and supports a wide range of data types

For a complete list of methods supported by JSONArray, visit the official documentation.

5.1. Creating JSONArray

Once we’ve initialized a JSONArray object, we can simply add and retrieve elements using the put() and get() methods:

JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");

JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");

ja.put(jo);

Following are the contents of our JSONArray (code is formatted for clarity):

[
    true,
    "lorem ipsum",
    {
        "city": "chicago",
        "name": "jon doe",
        "age": "22"
    }
]

5.2. Creating JSONArray Directly From JSON String

Like JSONObject, the JSONArray also has a constructor that creates a Java object directly from a JSON String:

JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");

This constructor may throw a JSONException if the source String isn’t a valid JSON String.

5.3. Creating JSONArray Directly From a Collection or an Array

The constructor of JSONArray also supports collection and array objects as arguments.

We simply pass them as an argument to the constructor, and it will return a JSONArray object:

List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");

JSONArray ja = new JSONArray(list);

Now our JSONArray consists of the following:

["California","Texas","Hawaii","Alaska"]

5.4. Removing a Specific Element From a JSONArray

We can remove a particular element using the instance method remove(int index). Let’s continue with the example JSONArray called ja for states and remove the “Alaska” state element using the remove(int index) method:

ja.remove(3);

Afterward, let’s list the remaining JSONArray:

System.out.println(ja.toString());

Indeed, it does not list the removed element:

["California","Texas","Hawaii"]

Further, we can find the element removed from the remove(int index) method call itself since it returns the element that it removes:

Object removed=ja.remove(3);
System.out.println(removed);

Indeed, it lists the removed element:

Alaska

Furthermore, the JSONArray reduces its size by 1 on removing an element. Notably, the index position in a JSONArray is zero-based. Therefore, the first element is at index 0. Accordingly, if we were to try removing the same element with the method call ja.remove(4), assuming the 4th element to be at index 4, the element won’t get removed. However, the method call with a non-existing index position doesn’t throw an exception/error. Therefore, we should verify the removal of an element, as we did.

6. JSONTokener

A JSONTokener takes a source String as input to its constructor and extracts characters and tokens from it. It’s used internally by classes of this package (like JSONObject, JSONArray) to parse JSON Strings.

There may not be many situations where we’ll directly use this class since we can achieve the same functionality using other simpler methods (like string.toCharArray()):

JSONTokener jt = new JSONTokener("lorem");

while(jt.more()) {
    Log.info(jt.next());
}

Now we can access a JSONTokener like an iterator, using the more() method to check if there are any remaining elements and next() to access the next element.

Here are the tokens received from the previous example:

l
o
r
e
m

7. CDL

We’re provided with a CDL (Comma Delimited List) class to convert comma-delimited text into a JSONArray and vice versa.

7.1. Producing JSONArray Directly From Comma-Delimited Text

To produce a JSONArray directly from the comma-delimited text, we can use the static method rowToJSONArray(), which accepts a JSONTokener:

JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));

Here’s what our JSONArray consists of now:

["England","USA","Canada"]

7.2. Producing Comma-Delimited Text From JSONArray

Let’s see how to perform the reverse of the previous step and get back the comma-delimited text from JSONArray:

JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);

The String cdt now contains the following:

England,USA,Canada

7.3. Producing JSONArray of JSONObjects Using Comma-Delimited Text

To produce a JSONArray of JSONObjects, we’ll use a text String containing both headers and data separated by commas.

We separate the different lines using a carriage return (\r) or line feed (\n).

The first line is interpreted as a list of headers, and all the subsequent lines are treated as data:

String string = "name, city, age \n" +
  "john, chicago, 22 \n" +
  "gary, florida, 35 \n" +
  "sal, vegas, 18";

JSONArray result = CDL.toJSONArray(string);

The object JSONArray result now consists of the following (output formatted for the sake of clarity):

[
    {
        "name": "john",
        "city": "chicago",
        "age": "22"
    },
    {
        "name": "gary",
        "city": "florida",
        "age": "35"
    },
    {
        "name": "sal",
        "city": "vegas",
        "age": "18"
    }
]

Notice that both data and header were supplied within the same String. We have an alternative way of doing this where we can achieve the same functionality by supplying a JSONArray to get the headers and a comma delimited String working as the data.

Again, we separate different lines using a carriage return (\r) or line feed (\n):

JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");

String string = "john, chicago, 22 \n"
  + "gary, florida, 35 \n"
  + "sal, vegas, 18";

JSONArray result = CDL.toJSONArray(ja, string);

Here we’ll get the contents of object result exactly as before.

The Cookie class deals with web browser cookies and has methods to convert a browser cookie into a JSONObject and vice versa.

Here are the main methods of the Cookie class:

  1. toJsonObject(String sourceCookie) – converts a cookie string into a JSONObject
  2. toString(JSONObject jo) – reverse of the previous method, converts a JSONObject into a cookie String

To convert a cookie String to a JSONObject, we’ll use the static method Cookie.toJSONObject():

String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
JSONObject cookieJO = Cookie.toJSONObject(cookie);

Now we’ll convert a JSONObject into a cookie String. This is the reverse of the previous step:

String cookie = Cookie.toString(cookieJO);

9. HTTP

The HTTP class contains static methods that are used to convert HTTP headers to a JSONObject and vice versa.

This class also has two main methods:

  1. toJsonObject(String sourceHttpHeader) – converts a HttpHeader String to a JSONObject
  2. toString(JSONObject jo) – converts the supplied JSONObject to a String

9.1. Converting JSONObject to HTTP Header

We use the HTTP.toString() method to convert a JSONObject to an HTTP header String:

JSONObject jo = new JSONObject();
jo.put("Method", "POST");
jo.put("Request-URI", "http://www.example.com/");
jo.put("HTTP-Version", "HTTP/1.1");
String httpStr = HTTP.toString(jo);

Here is what our String httpStr will consist of:

POST "http://www.example.com/" HTTP/1.1

Note that while converting an HTTP request header, the JSONObject must contain “Method”, “Request-URI” and “HTTP-Version” keys. And for the response header, the object must contain “HTTP-Version”, “Status-Code” and “Reason-Phrase” parameters.

9.2. Converting HTTP Header String Back to JSONObject

Here we will convert the HTTP string that we got in the previous step back to the very JSONObject we created in that step:

JSONObject obj = HTTP.toJSONObject("POST \"http://www.example.com/\" HTTP/1.1");

10. JSONException

Accordingly, the package-based applications throw the JSONException standard exception whenever any error is encountered.

The org.json package uses this class across all other classes. Furthermore, when an application throws this exception, it includes a message that states what exactly went wrong.

11. Parsing a JSON Boolean Value

The org.json.JSONObject is perhaps the most commonly used class for parsing a JSON boolean value in Java. Let’s explore parsing different representations of boolean values.

11.1. Parsing true and false

First, we create a JSONObject from a JSON string. Next, we obtain the value for the boolean property using the getBoolean(String) method:

@Test
void givenJSONString_whenParsed_thenCorrectBooleanValueReturned() {
    String json = """
                  { 
                      "name": "lorem ipsum",
                      "active": true,
                      "id": 1
                  }
                  """;
    JSONObject jsonObject = new JSONObject(jsonString);
    boolean active = jsonObject.getBoolean("active");
    assertTrue(active);
}

11.2. Parsing 0s and 1s

Typically, we represent JSON boolean values as true or false. However, some systems might use 0 and 1 to represent a boolean value.

We can fetch the integer value and use AssertJ assertion assertThat() to verify that its value is 1:

@Test
void givenJSONWithBooleanAs0Or1_whenParsed_correctBooleanValueReturned() {
    String json = """
                  { 
                      "name": "lorem ipsum",
                      "active": 1,
                      "id": 1
                  }
                  """;
    JSONObject jsonObject = new JSONObject(json);
    assertThat(jsonObject.getInt("active")).isEqualTo(1);
}

11.3. Parsing Mixed Representation of a JSON Boolean Value

Sometimes, we know that a JSON property contains a boolean value; however, we don’t know whether it is represented as true/false or 0/1. Again, we can create a JSONObject from the JSON string and further create an Object from the boolean property.

Thereafter, it’s straightforward. If the Object thus created is an instance of Integer, we’re using a numeric representation. Or, if the Object is an instance of Boolean, we are using booleans.

We can obtain the boolean value from the Object by casting it to the appropriate type:

@Test
void givenJSONWithMixedRepresentationForBoolean_whenParsed_thenCorrectBooleanValueReturned() {
    JSONObject jsonObject = new JSONObject(json);
    Object activeObject = jsonObject.get("active");
    if (activeObject instanceof Integer value) {
        assertTrue(value == 1);
    } else if (activeObject instanceof Boolean value) {
        assertTrue(value);
      }  
}

12. Conclusion

In this article, we looked at a JSON library using Java — org.json — and we focused on some of the core functionality available here.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)