Post data using rest assured. Method 4. If one form field is a map of key value pairs

Second method –Here courses is not a list but instead a map of key value pairs.So we create a Student Class and we also create another object named Course.

And since we only have one map in course below so all we do in Student class is make a reference to Course class in Student.

So we have a body where courses contain key value pairs

Body:
{
    "firstName": "h",
    "lastName": "s",
    "email": "hsd@example.com",
    "programme": "Computer Science",
    "course": {
        "name": "Java",
        "score": "34"
    }
}

Lets make a student class

Student class
package postreqexample1;
import java.util.ArrayList;
import java.util.List;

public class Student {
public String firstName;
public String lastName;
public String email;
public String programme;
public Course course;
    
    
public Student(String firstName, String lastName, String email, String programme) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.programme = programme;
        
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getProgramme() {
return programme;
}

public void setProgramme(String programme) {
this.programme = programme;
}

public Course getCourse() {
return course;
}
    
public void setCourse(Course course) {
this.course = course;
}
}

Noe lets make a Course class

package postreqexample1;

public class Course {
    
public String name;
public String score;

public Course(String name,String score) {
this.name = name;
this.score = score;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
  
public String getScore() {
return score;
}

public void setScore(String score) {
this.score = score;
 }
}

Now we got both the classes i.e Student and course . So now lets create a post request using rest assured

package postreqexample1;
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import postreqexample1.Student;

public class PostReqEx1 {
    
    
@Test
public void test001() {

RestAssured.baseURI = "http://localhost";
RestAssured.port = 8080;
RestAssured.basePath = "/student";

 Student student = new Student("h,"s","hsd@example.com","Computer Science");
 student.setCourse(new Course("Java","34"));

Response resp = given().contentType(ContentType.JSON).log().body().body(student).post();
resp.prettyPrint();
 }
}