如何在spring中使用列表< entity>以外的多个属性返回自定义响应

avwztpqn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(211)

我正在尝试从spring rest控制器获取一个自定义响应,返回给用户,其中包含所有注册用户的列表和sucess等其他键。我尝试了以下方法,但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数组在请求之后正确地显示出来?

w9apscun

w9apscun1#

您可以让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);
    }
}

注意,我为错误消息添加了一个单独的消息字段。我发现,如果某个特定字段不用于不同类型的数据,客户会更高兴。”“info”不应该是工人列表以外的任何内容,“message”不应该是字符串以外的任何内容。
免责声明:我没有一个springboot项目设置来正确测试这个。如果有什么不工作让我知道,我会检查它。

相关问题