1

I want to return json response something like this in spring boot :

{
   "status" : true,
   "message" : "Data is found",
   "data" : single object or list of object
}

My RestController look like this

@GetMapping("/users")
public JSONObject getAllUsers() {
    List<User> user = repository.findAll(); // get all users from db            
    JSONObject jsonObject = new JSONObject();

    jsonObject.put("status", true);
    jsonObject.put("message", "Data is found");
    jsonObject.put("data", user);

    return jsonObject;
}

But I am getting response something like this

{
 "empty": false
}

So, how can I return json reponse in the format like I mentioned above ?

Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
Milan Budhathoki
  • 61
  • 2
  • 3
  • 7

4 Answers4

4

You can simply return an object with those attributes. For example declare a new class that represents your desired response:

public class UserResponse {
    private Boolean status;
    private String message;
    private List data;

    public UserResponse(){
    }

    // setters & getters
}

And then change your controller:

@GetMapping("/users")
public UserResponse getAllUsers() {
    List<User> user = repository.findAll(); // get all users from db

    UserResponse userResponse = new UserResponse();

    userResponse.setStatus(true);
    userResponse.setMessage("Data is found");
    userResponse.setData(user);

    return userResponse;
}

For an in depth explanation of what was wrong with your approach you can check this answer

delephin
  • 1,085
  • 1
  • 8
  • 10
3

You can use the following way, so that you respond any data you want. I have been using this for long time.

public class ApiResponse {

    private boolean status;
    private String message;
    private Object data;
    private ErrorCode errorCode;

    //use constructors instead of setters
    
    //getters
}
Alexpandiyan Chokkan
  • 1,025
  • 1
  • 10
  • 30
0

1. Simple fastest Solution is :

You can return a Map as returned type to get JSON data in client as below

@GetMapping("/users")
public Map<String,?> getAllUsers() {
    List<User> user = repository.findAll(); // get all users from db
    
    Map<String, List> map = new HashMap<String, List>(); // use new HashMap<String, Object>(); for single result

    map.put("status", true);
    map.put("message", "Data is found");
    map.put("data", user);

    return map;
}

2. Other Solution by creating a custom response Class :

Here you'll create a model for all your response : as below

Model Response :

public class ResponseModel<T> {
    
    private Boolean status;
    private String message;
    private T data;
    
    
    public Boolean getStatus() {
        return status;
    }
    public void setStatus(Boolean status) {
        this.status = status;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
}

you controller should looks like

@GetMapping("/users")
public ResponseModel<?> getAllUsers() {

    List<User> users = repository.findAll();

    ResponseModel response = new ResponseModel<List<User>>();
    // use ResponseModel<User>(); constuructor for a single user response

    response.setStatus(true);
    response.setMessage("Data is found");
    response.setData(users);

    return response;
}
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
  • The `Map` raw type makes me sad, as does the assignment of a `Object` valued map to a `List` valued one. – Boris the Spider Nov 08 '20 at 08:22
  • @BoristheSpider I've added a class model response , but could you please elaborate why returning a map would be a bad idea , thnx ps: in map generic type , agreed changed to List ( according to returned type ) – Bourbia Brahim Nov 08 '20 at 08:39
-2

You can use GSON dependency in springboot,

 @GetMapping("/users")
 public String getAllUsers() {
     Gson gson = new Gson();
     List < User > user = repository.findAll(); // get all users from db
     JSONObject jsonObject = new JSONObject();
     jsonObject.put("status", true);
     jsonObject.put("message", "Data is found");
     jsonObject.put("data", user);
     String jsonInString = gson.toJson(jsonObject);
     return jsonInString;
 }
Gopi krishna
  • 308
  • 1
  • 9