[英]Using RestTemplate.exchange with an inconsistent API response
By inconsistent I mean that variable types can differ depending on the API response.不一致是指变量类型可能因 API 响应而异。 So a named variable could be an Object, a List of Objects, or bizarrely even a String.因此,命名变量可能是 Object、对象列表,甚至奇怪的是字符串。 I do not and cannot control the third-party API I'm consuming.我没有也无法控制我正在使用的第三方 API。
I'm using restTemplate.exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
, and the top-level responseType is consistent.我正在使用restTemplate.exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
,并且顶层 responseType是一致的。 It's in the child (and descendant) objects where the types may differ.它在类型可能不同的子(和后代)对象中。
Am I stuck with pivoting to consuming the API response as a String, and do manual parsing?我是否坚持将 API 响应作为字符串使用,并进行手动解析? Or is there a way to handle the fact that the variable types might map differently (similar to how GSON supports custom serialisation / deserialisation).或者有没有办法处理变量类型可能不同的事实 map (类似于 GSON 如何支持自定义序列化/反序列化)。
Managed to find a way through this.设法找到了解决这个问题的方法。 I did have to read the API response as a String and take it from there.我确实必须将 API 响应作为字符串读取并从那里获取。 General steps:一般步骤:
restTemplate.exchange
into String response body restTemplate.exchange
成字符串响应体Now, this won't be ideal for everyone - in a perfect world you shouldn't have to relax the JSON parsing rules at all.现在,这对每个人来说都不是理想的——在一个完美的世界里,你根本不必放松 JSON 解析规则。 This is all because I'm handling a very inconsistent API.这都是因为我正在处理一个非常不一致的 API。
Rough code example is as-follows (as our internal stack is pretty complex, so I've had to drag bits out from classes here and there):粗略的代码示例如下(因为我们的内部堆栈非常复杂,所以我不得不到处从类中拖出一些位):
String exampleEndpoint = Constants.EXAMPLE_ENDPOINT;
ResponseEntity<String> responseEntity = restTemplate.exchange(uri.toString(), HttpMethod.GET, null, String.class);
String stringResponse = responseEntity.getBody();
ExamplePOJO examplePojo = null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
try {
examplePojo = mapper.readValue(stringResponse, ExamplePOJO.class);
} catch (JsonProcessingException | NullPointerException ne) {
// JsonProcessingException is from readValue, NPE is to catch the string response
// being null in the event you don't want to let it bubble up further
logger.error(ne.getLocalizedMessage());
}
i think you need to change the httpmethod我认为您需要更改httpmethod
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.