0

我正在尝试将 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
    }
}
4

1 回答 1

2

这是使用 Jackson 将 JSON 响应映射到对象的一种非常奇怪的方式。我假设您只想能够使用实用程序类映射任意类?这是一个更简单的方法来完成此操作的示例。请注意,这使用了ObjectMapperJackson 发行版附带的类:

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);
于 2013-01-03T03:14:42.343 回答