How to parse a json with dynamic property name in java?

Solution 1:

If you just want to get the value of dynamic field name (e.g., "GvyArEFkg6JX6wI" in your case), you can just deserialize the response body to a Map and then traverse its value as follows:

ResponseEntity<String> finalResponse = aepClient.exchange(uri, HttpMethod.GET, entity, String.class);

ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> result = objectMapper.readValue(finalResponse.getBody(), Map.class);
result.values().forEach(System.out::println);

Console output:

{entityId=GvyArEFkg6JX6wI, mergePolicy={id=9245a39d-fe1a-4b33-acab-9bc5cbabf37c}}


And if you want to deserialize the response body to your DTO (I assume that there is only ONE root-level property), you can modify the DTO like:

public class AdobeResponseDto {
    private AdobeResponseFinal adobeResponseFinal;

    @JsonAnySetter
    public void setAdobeResponseFinal(String name, AdobeResponseFinal value) {
        adobeResponseFinal = value;
    }

    @JsonAnyGetter
    public AdobeResponseFinal getAdobeResponseFinal() {
        return adobeResponseFinal;
    }
}

Then you can get similar result as follows:

ResponseEntity<String> finalResponse = aepClient.exchange(uri, HttpMethod.GET, entity, String.class);
AdobeResponseDto adobeResponseDto = objectMapper.readValue(finalResponse.getBody(), AdobeResponseDto.class);
System.out.println(adobeResponseDto.getAdobeResponseFinal().toString());

Console output:

AdobeResponseFinal{entityId='GvyArEFkg6JX6wI', mergePolicy=MergePolicy{id='9245a39d-fe1a-4b33-acab-9bc5cbabf37c'}}