Get Values of Different Types from JSON Object in Java



We often need to extract values from a JSON object. In this article, we will learn how to get the values of the different types from a JSON object in Java.

What is JSONObject?

Java JSONObject is a class in the org.json package that represents a JSON object. Refer JSONObject for more information. Let's see the steps to get the values of different types from a JSON object in Java.

Getting different values from a JSON object

Before we start, let's add the required library to our program. We can add a .jar file, or we can use a Maven dependency.

Step 1: We will use the org.json library in this example. You can download the jar file from here. We can also use Maven dependency. Add the following dependency to your pom.xml file.

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

Step 2: Now, let's take a look at the program to get the values of different types from a JSON object.

  • Import the required classes: org.json.JSONObject and org.json.JSONException.
  • Create a JSONObject object and pass the JSON string to it.
  • Use the getString(), getInt(), getDouble(), and getBoolean() methods to extract the values of different types from the JSON object.
  • Print the extracted values to the console.

Example

The following is a demonstration of how to get the values of different types from a JSON object in Java.

import org.json.*;

public class JSONObjectTypeValuesTest {
   public static void main(String[] args) throws JSONException {
      JSONObject jsonObj = new JSONObject(
                "{" +
                ""Name" : "Ansh"," +
                ""Age" : 22, " +
                ""Salary": 10000000.00, " +
                ""IsSelfEmployee": false " +
                "}"
      );
      // returns string
      System.out.println(jsonObj.getString("Name")); 
      // returns int
      System.out.println(jsonObj.getInt("Age")); 
      // returns double
      System.out.println(jsonObj.getDouble("Salary")); 
      // returns true/false(boolean)
      System.out.println(jsonObj.getBoolean("IsSelfEmployee"));
   }
}

Following is the output of the above program -

Ansh
22
10000000.0
false
Updated on: 2025-04-22T16:05:02+05:30

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements