I got a response to my request:
[
{
"data":{
"channel":{
"id":"708087644",
"__typename":"User"
}
},
"extensions":{
"durationMilliseconds":112,
"operationName":"ViewerCardModLogsMessagesBySender",
"requestID":"01GWVKPD13BQGBZS64TY4824B9"
}
}
]
I am trying to create a Java class where I can parse this response:
ResponseEntity<RestResponse> result = restTemplate.postForEntity(uri, entity, RestResponse.class);
However, I still got an exception:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `org.tomass.twitch.RestResponse` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (PushbackInputStream); line: 1, column: 1]
RestResponse
looks like this:
public class RestResponse implements Serializable {
private static final long serialVersionUID = 1L;
private List<Root> root = new ArrayList<>();
public List<Root> getRoot() {
return root;
}
public void setRoot(List<Root> root) {
this.root = root;
}
public static class Root {
private Data data;
// getters & setters
public class Data {
private Channel channel;
// getters & setters
}
}
}
When editing the response and the name of the root list then it works: "{"root":
but I don’t know how to parse it without it.
2
Answers
There is no way to explicitly ask
RestTemplate
to deserialize intoList<Root>
, but you can askObjectMapper
! (if you are using Spring, there is one already available in context) The trick is to store type information intoTypeReference<T>
.With RestTemplate you could fetch an array of entities and convert it to a list:
If you need an unmodifiable list you could use
List.of()
orArrays.asList()
.Converting with ObjectMapper you could do a similar thing: