3

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

4
  • Have you debugged your code and made sure that the List or the HashSet doesn't contain two objects instead of one? Commented Jan 23, 2018 at 18:41
  • Additionally can you inspect the value of new ResponseEntity and post that? I realzie you cant populate the set twice, so I think you're doing something very odd at the end. Why do you not explicitly state the type of your response entity? Also, no need to loop, just try this Set<String> s = new HashSet<String>(service.getRoles()); Commented Jan 23, 2018 at 18:43
  • convert the hashset to list. so this.data = new ArrayList<String>(data);. Let me know if that works Commented Jan 23, 2018 at 18:54
  • /get is a very interesting choice for an endpoint. Just for giggles, change it to something else and change @RequestMapping to @GetMapping Commented Jan 23, 2018 at 19:21

2 Answers 2

1

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

} `

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.