我試圖將json api響應映射到對象,並且IntelliJ正在抱怨。這是說cannot resolve method readValue(java.lang.String, java.lang.Object[]);
。我意識到我沒有通過正確的參數,但我試過responseClass.class
和responseClass.getClass()
沒有運氣。如何將正確的對象傳遞給mapper.readValue()
用法:
MyClass myClass = new MyClass();
myClass.setResponseClass(User.class);
定義:
MyClass {
private Object responseClass;
public void setResponseClass(Object responseClass) {
this.responseClass = responseClass;
}
public Object getResponseClass() {
return responseClass;
}
public void getApiResponse() {
//some code here
ObjectMapper mapper = new com.MyApp.Utility.ObjectMapper();
//some code here
//I've tried responseClass.class and responseClass.getClass(), it didn't like either of them
mapper.readValue(response, responseClass);
//more code here
}
}
爲什麼不將** responseClass **聲明爲** private Object responseClass **?當你想獲得一個實例對象的類對象時,做出responseClass.class或responseClass.getClass()將不起作用,因爲你正在獲得一個類對象的類對象。 – BevynQ
什麼是'com.MyApp.Utility.ObjectMapper'?您是否包裝了Jackson ObjectMapper?此外,你已經抹去了你的類型被映射,通過將其存儲爲一個「對象」。 – Perception