如何为自定义响应模型获取格式精美的ResponseEntity?

问题描述 投票:0回答:1

[当我为ResponseEntity返回String时,它在邮递员中显示格式漂亮的json,但当我为ResponseEntity返回CustomModel时,它显示非格式的json。

代码1:

@PostMapping("/json1")
ResponseEntity<String> getData1() {

    String result = "{\"name\":\"Alex\"}";
    return ResponseEntity.ok().body(result);
}

邮递员输出1:

{
  "name": "Alex"
}

代码2:

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

邮递员输出2:

{
    "data": {
        "headers": {},
        "body": "{\"name\":\"Alex\"}",
        "statusCode": "OK",
        "statusCodeValue": 200
    }
}

为什么我没有格式化"{\"name\":\"Alex\"}"?如何在Postman中获取格式正确的json?

json spring spring-boot http resttemplate
1个回答
0
投票

您可以通过多种方式来做。

带有专用对象:

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);
© www.soinside.com 2019 - 2024. All rights reserved.