我正在尝试将json api响应映射到一个对象,而IntelliJ正在抱怨。它在说cannot resolve method readValue(java.lang.String, java.lang.Object[]);
。我意识到我没有传递正确的参数,但我已经尝试了responseClass.class
和responseClass.getClass()
而没有运气。
用法:
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
}
}
答案 0 :(得分:2)
这是使用Jackson将JSON响应映射到对象的一种非常奇怪的方式。我假设您只想使用实用程序类映射任意类?这是一个更容易实现这一目标的例子。请注意,这使用了杰克逊发行版附带的ObjectMapper
类:
public class JSONUtil {
private ObjectMapper mapper = new ObjectMapper();
public JSONUtil() {
super();
// Set ObjectMapper configuration and properties here
}
public <T> T deserialize(final String response, final Class<T> responseClass) {
if(response == null || responseClass == null) return null;
return mapper.readValue(response, responseClass);
}
}
现在, 仍然可以使用您发布的课程从JSON映射您的回复,并进行一些修改:
public class MyClass<T> {
private Class<T> responseClass;
public MyClass(final Class<T> responseClass) {
super();
this.responseClass = responseClass;
}
public void getApiResponse(final String response) {
final ObjectMapper mapper = new ObjectMapper();
final T values = mapper.readValue(response, responseClass);
//more code here
}
}
并使用它:
MyClass<User> myClass = new MyClass<User>(User.class);
myClass.getApiResponse(someJsonString);