简体   繁体   中英

Using Jackson object mapper with Spring Oauth2RestTemplate

I have an api response of the following form:

{
    "data": [
        {
            "field1": "string_1",
            "field2": 2,
            "field3": "string_3",
            "field4": "string_4"
        }
    ]
}

which can also be empty:

{
    "data": []
}

I am calling the API in the following way:

apiResponse = oAuth2RestTemplate.exchange(theURL, HttpMethod.GET, requestEntity, APIResponse.class);

I have no control over configuring oAuth2RestTemplate , but I can define the APIResponse class. How should I define it in a way that the line above does not return the following exception:

org.springframework.http.converter.HttpMessageConversionException: Type definition error: ... cannot deserialize from Object value (no delegate- or property-based Creator)

Here is what I have so far:

public class DataElements {
    private String field1;
    private int field2;
    private String field3;
    private String field4;

    // constructor and getters and setters
}

and

@JsonSerialize
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
public class APIResponse {

    List<DataElements> data;

    // constructor and getters and setters
}

As specified on the Jackson github , it does not require your classes to have the default constructor, but it will try to use it if nothing else is available.

Either add the default constructor to your APIResponse class or instruct jackson to use an another constructor, specified by you. This can be achieved by annotating the other constructor with @JsonCreator and then also its parameters with @JsonProperty , see the annotation docs

So you would end up with something like this:

@JsonSerialize
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
public class APIResponse {

    List<DataElements> data;

    @JsonCreator
    public APIResponse(@JsonProperty("data") List<DataElements> data) {
        this.data = data;
    }

    // getters and setters
}

I don't know if this is a good way or not, maybe you can try it

ObjectMapper mapper = new ObjectMapper();

ResponseEntity<JSONObject> jsonResponse = oAuth2RestTemplate.exchange(theURL, HttpMethod.GET, requestEntity, JSONObject.class);
JSONObject response = mapper.convertValue(jsonResponse.getBody(), new TypeReference<JSONObject>(){});   

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