我有兩種具有完全相同主體的方法。只有第二個引數(Class 或 TypeReference)不同。我怎樣才能用這種方法制作一種方法,或者至少提取身體以免重復?謝謝。
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
uj5u.com熱心網友回復:
這可能會幫助您查看它。一種方法將具有該功能,而其他方法將充當使用的助手。我們不能忽略變數“Class and TypeReference”,因為它在 objectMapper 中使用。
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass , TypeReference<T> typeReference) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
if(typeClass != null){
result = objectMapper.readValue(e.getResponseBody(), typeClass);
}else{
result = objectMapper.readValue(e.getResponseBody(), typeReference);
}
} catch (IOException ioException) {
System.out.println("Json Mapper Error : " ioException);
}
return result;
}
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass) {
return mapResponseBody(e, typeClass, null);
}
public static <T> T mapResponseBody(ApiException e, TypeReference<T> typeReference) {
return mapResponseBody(e, null, typeReference);
}
uj5u.com熱心網友回復:
您可以使用 TypeReference 更改您的方法,您將在 Class 中對其進行轉換并呼叫其他方法。
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
result = objectMapper.readValue(e.getResponseBody(), type);
} catch (IOException ioException) {
log.error("Json Mapper Error",ioException);
}
return result;
}
public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {
Class<?> typeClass = TypeFactory.defaultInstance().constructType(type).getRawClass();
return mapResponseBody(e, typeClass);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360121.html
標籤:爪哇
