Skip to content
Advertisement

How to Map Object response to another ObjectDto in java

I have to map rest template response to my DTO with different key and values. currently I am getting this json response from rest api

{
    "access_token": "7ada1efc-f159-42fa-84b9-f15b2a0ee333",
    "refresh_token": "1c9f5a71-40ae-4979-90db-088c2aa44123",
    "token_type": "bearer",
    "scope": null,
    "expires_in": 1440
}

And I want to map it into my DTO for me able to save into DB

@Data
public class AuthIntegrationTokenDto {

    private long id;
    private int cmsIntegrationId;
    private String token;
    private String refreshToken;
    private String createdBy;
    private String lastUpdatedBy;

}

What i want is to get only same key dynamically to match with the response of api above. Currently I am doing this but it seems that I am not setting correct value of same keys.

ResponseEntity<Object> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                request,
                Object.class,
                "client_credentials"
        );


        Object result = response.getBody();

        JSONObject json = new JSONObject((Map) result);
        AuthIntegrationTokenDto authIntegrationTokenDto = new AuthIntegrationTokenDto();

        for (Object o : json.entrySet()) {
            Map.Entry entry = (Map.Entry) o;

            authIntegrationTokenDto.setToken(String.valueOf(entry.getValue()));
            authIntegrationTokenDto.setRefreshToken(String.valueOf(entry.getValue()));

        }

After executing this I am getting null values in my db.

enter image description here

Advertisement

Answer

You are not setting the values to the DTO correctly. You must get the key first and then set it:

 for (Object o : json.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            if(entry.getKey() == 'access_token') {
            authIntegrationTokenDto.setToken(String.valueOf(entry.getValue()));
            } else if(entry.getKey() == 'refresh_token') {
            authIntegrationTokenDto.setRefreshToken(String.valueOf(entry.getValue()));
            }
        }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement