[英]How to de-serialize a raw array of arrays from REST response using Springboot RestTemplate
I am using SpringBoot RestTemplate to consume a REST API.我正在使用 SpringBoot RestTemplate 来消耗 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:响应正文由 arrays 数组组成,每个嵌套的 arrays 都有一个键值对,类似于:
[
["michael",0.9227975606918335],
["frank",0.888996958732605],
["christian",0.887883722782135]
]
This JSON structure isn't ideal, of course, but I have to work with it.当然,这个 JSON 结构并不理想,但我必须使用它。 I would like to deserialize this response to a Java object that has one field (2-dim array).我想将此响应反序列化为具有一个字段(2-dim 数组)的 Java object。
The API is called like this: API 是这样调用的:
GetResponse response = restTemplate.getForObject(url, GetResponse.class);
The Java class structure looks like this (all annotated with Lombok's @NoArgsConstructor, @AllArgsConstructor, @Getter, @Setter): Java class 结构看起来像这样(全部用 Lombok 的 @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?任何想法所需的 class 结构是什么样的? Am I missing a Jackson annotation anywhere?我在任何地方都缺少 Jackson 注释吗? Note that I do get a response so the problem is clearly with the Deserialization.请注意,我确实收到了回复,因此问题显然与反序列化有关。 Thanks.谢谢。
You should map your response to KeyValuePair[].class
not to GetResponse.class
and add @JsonFormat(shape= JsonFormat.Shape.ARRAY)
annotation to KeyValuePair class. 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:键值对 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.