我正在尝试从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数组在请求之后正确地显示出来?
1条答案
按热度按时间w9apscun1#
您可以让spring引导处理响应实体的序列化。
创建一个定义响应对象的pojo。
这使您可以稍微简化getallworkers方法:
注意,我为错误消息添加了一个单独的消息字段。我发现,如果某个特定字段不用于不同类型的数据,客户会更高兴。”“info”不应该是工人列表以外的任何内容,“message”不应该是字符串以外的任何内容。
免责声明:我没有一个springboot项目设置来正确测试这个。如果有什么不工作让我知道,我会检查它。