gpt4 book ai didi

java - 如何将正确的对象传递给mapper.readValue()

转载 作者:行者123 更新时间:2023-12-02 07:21:42 24 4
gpt4 key购买 nike

我正在尝试将 json api 响应映射到对象,而 IntelliJ 正在提示。它说无法解析方法readValue(java.lang.String, java.lang.Object[]);。我意识到我没有传递正确的参数,但我尝试了 responseClass.classresponseClass.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
}
}

最佳答案

这是一种使用 Jackson 将 JSON 响应映射到对象的非常奇怪的方法。我假设您只是希望能够使用实用程序类映射任意类?这是实现此目的的更简单方法的示例。请注意,这使用 Jackson 发行版附带的 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);

关于java - 如何将正确的对象传递给mapper.readValue(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com