如何 return 在 Spring 中使用 List<Entity> 以外的多个属性自定义响应

How to return custom response in Spring with several attributes other than the List<Entity>

我正在尝试从 spring 休息控制器返回给用户的自定义响应,其中包含所有注册用户的列表和其他键,例如成功等。 我尝试了以下方法,但 Json 数组被完全转义为字符串...

@GetMapping(value = "/workers", produces = "application/json;charset=UTF-8")
public ResponseEntity<String> getAllWorkers() throws JSONException {
    JSONObject resp = new JSONObject();
    ObjectMapper objectMapper = new ObjectMapper();

    HttpStatus status;
    try {
        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        List<Worker> workers = workerservice.getAllworkers();
        String json = mapper.writeValueAsString(workers);
        
        resp.put("success", true);
        resp.put("info", json);
        status = HttpStatus.OK;
    } catch (Error | JsonProcessingException e) {
        resp.put("success", false);
        resp.put("info", e.getMessage());
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(resp.toString(),status);
}

我得到了这样的东西

{
    "success": true,
    "info": "[ {\n  \"id\" : 3,\n  \"password\" : \"abcdefg\", \n  \"tasks\" : [ ], (...) ]"
}

想要这样的东西:

{
    "success": true,
    "info": [ 
        {
           "id" : 3,
           "password" : "abcdefg",
           "tasks" : [ ]
        },
        (...) 
    ]"
}

有什么方法可以在请求后正确显示 json 数组?

您可以让 Spring 引导处理响应实体的序列化。

创建一个定义响应对象的 POJO。

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class WorkerPojo {
    @JsonProperty("success")
    private boolean success;
    @JsonProperty("info")
    private List<Worker> workerList;
    @JsonProperty("message")
    private String message;

    // A default constructor is required for serialization/deserialization to work
    public WorkerPojo() {
    }
    
    // Getters and Setters ....
}

这可以让您稍微简化 getAllWorkers 方法:

@GetMapping(value = "/workers", produces = "application/json;charset=UTF-8")
public ResponseEntity<WorkerPojo> getAllWorkers() throws JSONException {
    WorkerPojo response;
    try {
        List<Worker> workers = workerservice.getAllworkers();
        return new ResponseEntity<>(new WorkerPojo(true, workers, "OK"), HttpStatus.OK);
    } catch (Error e) {
        return new ResponseEntity<>(new WorkerPojo(false, null, e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

请注意,我为错误消息添加了一个单独的消息字段。我发现如果特定字段不用于不同类型的数据,客户会更开心。 “信息”永远不应是工作人员列表,“消息”永远不应是字符串。

免责声明:我没有 Spring 引导项目设置来正确测试它。如果有问题请告诉我,我会检查一下。