[当我为ResponseEntity返回String
时,它在邮递员中显示格式漂亮的json,但当我为ResponseEntity返回CustomModel
时,它显示非格式的json。
@PostMapping("/json1")
ResponseEntity<String> getData1() {
String result = "{\"name\":\"Alex\"}";
return ResponseEntity.ok().body(result);
}
{
"name": "Alex"
}
class RestResp {
public ResponseEntity<?> data = null;
}
@PostMapping("/json2")
ResponseEntity<RestResp> getData2() {
String result = "{\"name\":\"Alex\"}";
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(result);
return ResponseEntity.ok().body(response);
}
{
"data": {
"headers": {},
"body": "{\"name\":\"Alex\"}",
"statusCode": "OK",
"statusCodeValue": 200
}
}
为什么我没有格式化"{\"name\":\"Alex\"}"
?如何在Postman中获取格式正确的json?
您可以通过多种方式来做。
带有专用对象:
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
和
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(new Person("Alex"));
return ResponseEntity.ok().body(response);
将其映射到json:
String result = "{\"name\":\"Alex\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(result);
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(node);
return ResponseEntity.ok().body(response);
或仅使用地图:
Map<String,Object> map = new HashMap<>();
map.put("name", "Alex");
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(map);
return ResponseEntity.ok().body(response);