Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

What is ObjectMapper class?

Category: Rest Assured

We will use Class ObjectMapper to create a JSON Object or ObjectNode.

  • To create a JSON Object using Jackson, we need to use createObjectNode() method of ObjectMapper class which returns an ObjectNode class instance.
  • ObjectNode class has overloaded methods put(String fieldName, T fieldValue ) which takes field Name as String and values of different primitive and wrapper class types like String, Boolean etc.
  • All field names should be unique. If you pass duplicate field name, it will not throw any error but override field values by latest. It is similar to put() method of Map in Java.

To get the created JSON Object as string, use writeValueAsString() provided by ObjectMapper class. If you want in proper JSON format, use writerWithDefaultPrettyPrinter() method for formatting.

Example Code for Json Object:
{
  "firstname" : "Phani",
  "lastname" : "Nagula"
}

// Create an object to ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
		
// Creating Node that maps to JSON Object structures in JSON content
ObjectNode employeeDetails = objectMapper.createObjectNode();

employeeDetails.put("firstname", "Phani");
employeeDetails.put("lastname", "Nagula");

// To print created json object
String createdPlainJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeDetails);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);
Example Code for Nested Json Object:
{
	"employee" : {
			"firstname" : "Phani",
			"lastname" : "Nagula"
			}
}

// Create an object to ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
		
// Creating Node that maps to JSON Object structures in JSON content
ObjectNode employeeInfo = objectMapper.createObjectNode();
ObjectNode employeeDetails = objectMapper.createObjectNode();

employeeDetails.put("firstname", "Phani");
employeeDetails.put("lastname", "Nagula");

employeeInfo.set("employee", "employeeDetails");

// To print created json object
String createdPlainJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeInfo);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);

Leave a Reply

Your email address will not be published. Required fields are marked *