Home > Blockchain >  How to de-serialize a raw array of arrays from REST response using Springboot RestTemplate
How to de-serialize a raw array of arrays from REST response using Springboot RestTemplate

Time:02-08

I am using SpringBoot RestTemplate to consume a REST API. The response body consists of an array of arrays, with each of the nested arrays having a key value pair, similar to this:

[
    ["michael",0.9227975606918335],
    ["frank",0.888996958732605],
    ["christian",0.887883722782135]
]

This JSON structure isn't ideal, of course, but I have to work with it. I would like to deserialize this response to a Java object that has one field (2-dim array).

The API is called like this:

GetResponse response = restTemplate.getForObject(url, GetResponse.class);

The Java class structure looks like this (all annotated with Lombok's @NoArgsConstructor, @AllArgsConstructor, @Getter, @Setter):

    public class GetResponse {
        @JsonProperty
        private NamesArray[] data;
    }

    public class NamesArray {
        @JsonProperty
        private KeyValuePair[] data;
    }

    public class KeyValuePair {
        @JsonProperty
        private String key;

        @JsonProperty
        private float rating;
    }

This should work, but I keep getting this error:

org.springframework.web.client.RestClientException: Error while extracting response for type 
[class com.mypackage.Client$GetResponse] and content type [application/json]; nested exception is 
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot 
deserialize value of type `com.mypackage.Client$GetResponse` from Array value (token `JsonToken.START_ARRAY`); 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize value of type `com.mypackage.Client$GetResponsesponse` from Array value (token `JsonToken.START_ARRAY`)

Any ideas what the required class structure would look like? Am I missing a Jackson annotation anywhere? Note that I do get a response so the problem is clearly with the Deserialization. Thanks.

CodePudding user response:

You should map your response to KeyValuePair[].class not to GetResponse.class and add @JsonFormat(shape= JsonFormat.Shape.ARRAY) annotation to KeyValuePair class.

Something like this should work:

KeyValuePair class:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public static class KeyValuePair {
   private String key;
   private float rating;
}

Response:

KeyValuePair[] response = restTemplate.getForObject(url, KeyValuePair[].class);
  •  Tags:  
  • Related