简体   繁体   中英

JSON response from spring boot rest controller getting repeated

I was trying to build a rest api using Spring boot 1.5.9.RELEASE and been stuck on this issue. The post request to api end points works just fine but when comes to get requests the result gets repeated . The response which the app produces for get request is

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

The associated request mapping class code

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

The Response class

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

Any ideas about how to solve the issue? Thanks in advance

You are creating response twice, use below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM