0

I'm using RestTemplate to call an external API. Here is the result of the API call :

{
    "results": [
        {
            "code": "UDE",
            "usergroups": [
                {
                    "name": "Some name",
                    "users": [
                        {
                            "id": 457,
                            "login": "uid34",
                        }
                     ]
                }
            ]
        }
    ]
}

I'm only interested in getting the flat list of users.

  1. I don't want to return a JSON String and user gson to target the users node.
  2. I want to avoid creating too many wrappers.

So this is what I've done so far:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
@JsonInclude(Include.NON_NULL)
@JsonRootName("usergroups")
public class UserGroup{

    @JsonProperty("users")
    private List<User> users = new ArrayList<User>();

}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Response<T> {

    @JsonProperty("results")
    private List<T> results= new ArrayList<>();
    
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User{
     private Integer id;
     private String login;
}

    ResponseEntity<Response<UserGroup>> response = restTemplate.exchange(url, HttpMethod.GET, entity,
            new ParameterizedTypeReference<Response<UserGroup>>(){});

    List<User> users = response.getBody().getResults()
            .stream()
            .map(UserGroup::getUsers)
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

The API call works fine but the users property is always empty for all UserGroup I have. What am I doing wrong? Thanks for your help.

NB : I also tried this solution but I get an exception

sehueyl
  • 35
  • 4
  • WHat exception you are getting unmapped property? – Vova Bilyachat May 18 '21 at 07:34
  • With `@JsonRootName`, I'm not getting any exception. The value of `users` is just empty (while it should be filled with elements). When I try the solution given in the link, I get `org.springframework.http.converter.HttpMessageNotReadableException: Could not resolve type id 'id' into a subtype of` – sehueyl May 18 '21 at 08:42

0 Answers0