by BehindJava

How to return Java object as a return value in Spring Boot

Home » springboot » How to return Java object as a return value in Spring Boot

In this tutorial we are going to learn about returning Java object as a return that contains user details in response to get users API call.

Firstly, create a class with user’s details that are associated with getters and setters for the user details and an object is created in the controller class.

Sample Code Snippet:

package com.behindjava.tutorial.model;

public class UserModel {
	private String firstname;
	private String lastname;
	private String email;
	private String userId;
	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) { = email;
	public String getUserId() {
		return userId;
	public void setUserId(String userId) {
		this.userId = userId;

Once the above model class is created, return type of the get method is changed to the UserModel class and an instance of UserModel is created inside the getUser method and using setters we can assign values to the UserModel object and return the object.

Sample Code Snippet:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.behindjava.tutorial.model.UserModel;

public class UserController {

	@GetMapping(path = "/{userId}")
	public UserModel getUser(@PathVariable String userId) {
		UserModel um = new UserModel();
		um.setFirstname("Lakshmi Deepak");
		return um;


By default the object returned in postman is in the JSON representation. To make this change as per our requirement.

Previous                                                                                                               Next