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
How to construct a JSON object from a subset of another JSON object in Java?
In this article, we will learn how to construct a JSON object from a subset of another JSON object in Java. If you are not familiar with JSON and its usage in Java, you can refer to our JSON Overview tutorial.
JSON Object From a Subset of Another Object
There is more than one way to construct a JSON object from a subset of another JSON object in Java. Some of the popular libraries that we can use are -
- Using org.json library
- Using Gson library
- Using Jackson library
Let's see all of them in detail.
Using the org.json Library
Let's see how to construct a JSON object from a subset of another JSON object using the org.json library. The org.json library works with JSON data in Java. It provides classes and methods to create, parse, and manipulate JSON data.
First, we will need to add the org.json library. We can either download it from its official website or include it in our project if we are using Maven or Gradle. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency>
Next, we will create a JSON object. Then, we will create a new JSON object from a subset of the original JSON object. Finally, we will print the new JSON object.
Example
Below is the code that demonstrates how to construct a JSON object from a subset of another JSON object using the org.json library:
import org.json.JSONObject;
public class JsonSubsetExample {
public static void main(String[] args) {
// Original JSON object
JSONObject original = new JSONObject();
original.put("name", "Ansh");
original.put("age", 25);
original.put("city", "Delhi");
original.put("email", "ansh@example.com");
// Keys to include in the subset
String[] keysToInclude = {"name", "city"};
// Subset JSON object
JSONObject subset = new JSONObject();
for (String key : keysToInclude) {
if (original.has(key)) {
subset.put(key, original.get(key));
}
}
// Print the subset JSON object
System.out.println("Subset JSON: " + subset.toString(3));
}
}
Following is the output of the above code:
Subset JSON: {
"name": "Ansh",
"city": "Delhi"
}
Using the Gson Library
Let's see how to construct a JSON object from a subset of another JSON object using the Gson library. Gson is a library developed by Google to convert Java objects into JSON and back again.
Before we start, we need to add the Gson library to our project. You can download the library from its official website or include it in your project using a tool like Maven or Gradle if you are using them. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
Now, let us walk through the steps:
- As we have already added the Gson library, we can now create a JSON object.
- First, we will create a JSON object.
- Next, we will create a new JSON object from a subset of the original JSON object.
- Finally, we will print the new JSON object.
Example
Below is the code demonstrating how to construct a JSON object from a subset of another JSON object using the Gson library:
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class SubsetJsonWithGson {
public static void main(String[] args) {
// Step 1: Create original JSON object
String jsonString = """
{
"name": "Ansh",
"age": 25,
"city": "Delhi",
"email": "ansh@example.com"
}
""";
JsonObject original = JsonParser.parseString(jsonString).getAsJsonObject();
// Step 2: Define keys for subset
String[] keysToInclude = {"name", "city"};
// Step 3: Create subset JSON object
JsonObject subset = new JsonObject();
for (String key : keysToInclude) {
JsonElement value = original.get(key);
if (value != null) {
subset.add(key, value);
}
}
// Step 4: Print the subset JSON
System.out.println("Subset JSON:\n" + subset);
}
}
Following is the output of the above code:
Subset JSON:
{
"name": "Ansh",
"city": "Delhi"
}
Using the Jackson Library
Let's see how to construct a JSON object from a subset of another JSON object using the Jackson library. Jackson is a well-known library for processing JSON data in Java.
To use Jackson in your code, you will need to add it to your project. You can simply download it from the official website, or if you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency>
Next, we will create a JSON object. Then, we will create a new JSON object from a subset of the original JSON object. Finally, we will print the new JSON object.
Example
The following example demonstrates how to construct a JSON object from a subset of another JSON object using the Jackson library:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Set;
public class SubsetJsonWithJackson {
public static void main(String[] args) throws Exception {
// Step 1: Create ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
// Step 2: Original JSON as a string
String jsonString = """
{
"name": "Ansh",
"age": 25,
"city": "Delhi",
"email": "ansh@example.com"
}
""";
// Step 3: Parse the string into a JsonNode
JsonNode original = mapper.readTree(jsonString);
// Step 4: Define which fields to include in the subset
Set<String> keysToInclude = Set.of("name", "city");
// Step 5: Create a new ObjectNode for the subset
ObjectNode subset = mapper.createObjectNode();
for (String key : keysToInclude) {
if (original.has(key)) {
subset.set(key, original.get(key));
}
}
// Step 6: Print the subset JSON
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(subset);
System.out.println("Subset JSON:\n" + prettyJson);
}
}
Following is the output of the above code:
Subset JSON:
{
"name" : "Ansh",
"city" : "Delhi"
}