简体   繁体   English

如何在 Springboot 中返回 JSON 响应?

[英]How to return JSON response in Springboot?

I want to return json response something like this in spring boot :我想在 Spring Boot 中返回类似这样的 json 响应:

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

My RestController look like this我的 RestController 看起来像这样

@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 ?那么,如何以我上面提到的格式返回 json 响应?

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有关您的方法有什么问题的深入解释,您可以查看此答案

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
}

1. Simple fastest Solution is : 1.简单最快的解决方案是:

You can return a Map as returned type to get JSON data in client as below您可以返回一个 Map 作为返回类型以在客户端获取 JSON 数据,如下所示

@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 : 2.通过创建自定义响应类的其他解决方案:

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

You can use GSON dependency in springboot,你可以在 springboot 中使用 GSON 依赖,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM