简体   繁体   中英

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.

在此处输入图片说明

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

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