2

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 ?

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

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;
}

2 Comments

The Map raw type makes me sad, as does the assignment of a Object valued map to a List valued one.
@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 )
-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;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.