Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA).” This means that compiled Java code can be run on all different platforms that support Java. There’s no need for recompilation.
We can create a JSON Object using a Map in Java. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs.
To create a request body using JSON Object using HashMap, we need to add a Maven dependency.
I have created a simple Java map and filled it with the values that represent JSON properties.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
public class Json_Demo {
@Test
public void passBodyAsMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("employee_name", "MapTest");
map.put("employee_salary", "99999");
map.put("employee_age", "30");
map.put("profile_image", "test.png");
RestAssured.given()
.contentType(ContentType.JSON)
.body(map)
.log().all()
.when()
.post("https://dummy.restapiexample.com/api/v1/create")
.then()
.assertThat().statusCode(200)
.body("data.employee_name", equalTo("MapTest"))
.body("data.employee_age", equalTo("30"))
.body("data.employee_salary", equalTo("99999"))
.body("message", equalTo("Successfully! Record has been added.")).log().all();
}
}
The request body as well as the response body will look as shown below:-
Above one is a simple JSON Request Body. Let us take an example of a Complex Request Body or nested Request Body as shown below.
Let us create a Java program to understand this:
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
public class Json_Demo {
@Test
public void passBodyAsMultipleMap() {
// First JSON Object using Hash Map
Map<String, Object> data = new HashMap<String, Object>();
data.put("employee_name", "MapTest");
data.put("profile_image", "test.png");
// Second JSON Object using Hash Map
Map<String, String> msg = new HashMap<String, String>();
msg.put("updated_message", "Details of New Resource");
msg.put("employee_age", "30");
data.put("details", msg);
data.put("employee_salary", "99999");
RestAssured.given().contentType(ContentType.JSON).body(data).log().all()
// WHEN
.when().post("https://dummy.restapiexample.com/api/v1/create")
// THEN
.then().assertThat().statusCode(200).body("data.employee_name", equalTo("MapTest"))
.body("data.details.updated_message", equalTo("Details of New Resource"))
.body("data.details.employee_age", equalTo("30")).body("data.employee_salary", equalTo("99999"))
.body("message", equalTo("Successfully! Record has been added.")).log().all();
}
}
The request body as well as the response body will look as shown below image. The first part is the body of the request and the second part is the response provided by the API.
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Deserialization converts a stream of bytes into a Java object that we can use in code.
We use Jackson’s ObjectMapper, as we did for serialization, using readValue() to process the input. Also, note our use of Jackson’s TypeReference, which we’ll use in all of our deserialization examples to describe the type of our destination Map.
This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer to the below tutorials.
A HashMap stores items in “key/value”pairs, and you can access them by an index of another type (e.g. a String).
One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like String keys and String values. We need to import java.util.HashMap or its superclass in order to use the HashMap class and methods.
It is not an ordered collection, which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.
HashMap<String, String> employeeDetail = new HashMap<String, String>();
HashMap<String, String> employeeDetail = new HashMap<>();
HashMap<String, Integer> employeeDetail = new HashMap<String, Integer>();
Add Items
Below is an example where we are adding items to HashMap by using put() method.
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
/* This is how to declare HashMap of key and Value as String */
HashMap<String, String> employeeDetail = new HashMap<String, String>();
// Add keys and values (Name, Designation)
employeeDetail.put("Tim", "DBA");
employeeDetail.put("Dong", "SDET");
employeeDetail.put("Nisha", "BA");
employeeDetail.put("Ulana", "Dev");
System.out.println("Detail of Employees :" + employeeDetail);
}
}
The output of the above program is
Below is an example where we are adding items to HashMap by using put() method.
Here, the key is String, and the Value is Integer.
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
// Combination of String(key) and Integer(value)
HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
employeeAge.put("Tim", 25);
employeeAge.put("Dong", 26);
employeeAge.put("Nisha", 29);
employeeAge.put("Ulana", 34);
System.out.println("Age of Employees :" + employeeAge);
}
}
The output of the above program is
Access an Item
To access a value in the HashMap, use the get() method and refer to its key:-
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
// Combination of String(key) and Integer(value)
HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
employeeAge.put("Tim", 25);
employeeAge.put("Dong", 26);
employeeAge.put("Nisha", 29);
employeeAge.put("Ulana", 34);
System.out.println("Age of Employees :"+ employeeAge);
// Access a value
System.out.println("Access Value of Key Nisha :" + employeeAge.get("Nisha"));
}
}
The output of the above program is
Remove an Item
To remove an item, use the remove() method and refer to the key:
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
// Combination of String(key) and Integer(value)
HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
employeeAge.put("Tim", 25);
employeeAge.put("Dong", 26);
employeeAge.put("Nisha", 29);
employeeAge.put("Ulana", 34);
System.out.println("Age of Employees :" + employeeAge);
// To remove an item, use the remove() method and refer to the key
employeeAge.remove("Ulana");
System.out.println("List of Employee after removing Ulana :" + employeeAge);
}
}
The output of the above program is
To remove all items, use the clear()method:-
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
// Combination of String(key) and Integer(value)
HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
employeeAge.put("Tim", 25);
employeeAge.put("Dong", 26);
employeeAge.put("Nisha", 29);
employeeAge.put("Ulana", 34);
System.out.println("Age of Employees :" + employeeAge);
// To remove all items, use the clear() method:
employeeAge.clear();
System.out.println("List of Employes after clear:" + employeeAge);
}
}
The output of the above program is
Checking whether HashMap is empty or not
We are using isEmpty() method of the HashMap class to perform this check.
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
/* This is how to declare HashMap */
HashMap<String, String> employeeDetail = new HashMap<String, String>();
// Add keys and values (Name, Designation)
employeeDetail.put("Tim", "DBA");
employeeDetail.put("Dong", "SDET");
employeeDetail.put("Nisha", "BA");
employeeDetail.put("Ulana", "Dev");
System.out.println("Detail of Employees :" + employeeDetail);
// Checking whether HashMap is empty or not
System.out.println("Is HashMap Empty? " + employeeDetail.isEmpty());
// Delete all items from HasMap
employeeDetail.clear();
System.out.println("Is HashMap Empty now? " + employeeDetail.isEmpty());
}
}
The output of the above program is
Check if a particular key exists in HashMap
We will be using containsKey() method of the HashMap class to perform this check. This method returns a boolean value.
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
/* This is how to declare HashMap */
HashMap<String, String> employeeDetail = new HashMap<String, String>();
// Add keys and values (Name, Designation)
employeeDetail.put("Tim", "DBA");
employeeDetail.put("Dong", "SDET");
employeeDetail.put("Nisha", "BA");
employeeDetail.put("Ulana", "Dev");
System.out.println("Detail of Employees :" + employeeDetail);
// Check if a particular key exists in HashMap
boolean flag = employeeDetail.containsKey("Nisha");
System.out.println("Key Nisha exists in HashMap? : " + flag);
boolean flag1 = employeeDetail.containsKey("Shawn");
System.out.println("Key Shawn exists in HashMap? : " + flag1);
}
}
The output of the above program is
Check if a particular value exists in HashMap
We will be using containsValue()method of the HashMap class to perform this check.
import java.util.HashMap;
public class HashMap_Demo {
public static void main(String[] args) {
/* This is how to declare HashMap */
HashMap<String, String> employeeDetail = new HashMap<String, String>();
// Add keys and values (Name, Designation)
employeeDetail.put("Tim", "DBA");
employeeDetail.put("Dong", "SDET");
employeeDetail.put("Nisha", "BA");
employeeDetail.put("Ulana", "Dev");
System.out.println("Detail of Employees :" + employeeDetail);
// Check if a particular value exists in HashMap
boolean valueExists = employeeDetail.containsValue("Dev");
System.out.println("String Dev exists in HashMap? : " + valueExists);
boolean valueNotExists = employeeDetail.containsValue("Test");
System.out.println("String Test exists in HashMap? : " + valueNotExists);
}
}
The output of the above program is
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!