我使用第三方服务,它的表现很有趣。
它返回空列表的对象:
{
"list": {},
"total": 0
}
否则,返回列表
{
"list": [
{
"createdIndex": 118,
"key": "/apisix/services/00000000000000000117",
"modifiedIndex": 119
}
],
"total": 1
}
当我尝试在 Java 上反序列化它时,如果它不为空,我会得到 MismatchedInputException。
因为我的java类看起来像:
@Getter
@Setter
public class Response<T> {
@JsonProperty("error_msg")
private String errorMsg;
private String key;
private T value;
private List<Response<T>> list;
private int total;
}
有什么建议吗?
有一个解决方案适合您,您可以注册为 DeserializationProblemHandler 来识别非法令牌和名称,然后返回一个 List 实例(通常会)
class CustomDeserializationProblemHandler extends DeserializationProblemHandler {
public Object handleUnexpectedToken(DeserializationContext ctxt, JavaType targetType, JsonToken t, JsonParser p, String failureMsg)
throws IOException {
if (t == JsonToken.START_OBJECT && "list".equals(p.currentName())) {
return new ArrayList<>();
}
return handleUnexpectedToken(ctxt, targetType.getRawClass(), t, p, failureMsg);
}
}
public class Main{
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addHandler(new CustomDeserializationProblemHandler());
String input = "{\"list\":{},\"total\":0}";
Response<A> aResponse = objectMapper.readValue(input, new TypeReference<Response<A>>() {
});
System.out.println(aResponse);
}
}