Spring Boot 托控制器的JSON响应重复

dauxcl2d  于 2022-11-19  发布在  Spring
关注(0)|答案(2)|浏览(158)

我尝试使用Sping Boot 1.5.9.RELEASE构建一个rest api,但一直在这个问题上卡住了。对api端点的post请求工作正常但当遇到get请求时,结果会重复。应用为get请求生成的响应是

{"data":["Administrator"]}{"data":["Administrator"]}

关联的请求Map类代码

@RequestMapping("/get")
    public ResponseEntity getAllRoles()throws Exception{

        List<Roles> roles = rolesService.getRoles();
        Set<String> roleNames = new HashSet<>();
        for(Roles r : roles)
            roleNames.add(r.getRoleName());
        return new ResponseEntity(new Response(roleNames), HttpStatus.OK);
    }

Response类

public class Response<T> {

    private T data;

    public Response() {}

    public Response(T data) {
            this.data = data;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

有什么解决办法吗?先谢谢了

x7rlezfr

x7rlezfr1#

您正在创建两次响应,请使用以下内容

RequestMapping("/get")
    public ResponseEntity<?> getAllRoles()throws Exception{

        List<Roles> roles = rolesService.getRoles();
        Set<String> roleNames = new HashSet<>();
        for(Roles r : roles)
            roleNames.add(r.getRoleName());
        return new ResponseEntity<Object>(roleNames, HttpStatus.OK);
    }
jv4diomz

jv4diomz2#

在getter方法中注入@JsonProperty(“yourFiledName”)对我很有效。

private T data;

public Response() {}

public Response(T data) {
        this.data = data;
}

@JsonProperty("data")
public T getData() {
    return data;
}

public void setData(T data) {
    this.data = data;
}

} `

相关问题