
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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