Jovin Thariyath
Jovin Thariyath

Reputation: 76

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

Upvotes: 3

Views: 1634

Answers (2)

Bablu
Bablu

Reputation: 326

Injecting @JsonProperty("yourFiledName") at the getter method works for me. ` public class Response {

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

} `

Upvotes: 0

kj007
kj007

Reputation: 6254

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

Upvotes: 1

Related Questions