简体   繁体   English

如何将 Jackson ObjectMapper.readValue 与泛型类一起使用

[英]How to use Jackson ObjectMapper.readValue with generic class

how to use Jackson ObjectMapper.readValue with generic class, someone says that need JavaType, but JavaType is also splicing other class, is Jackson can use like gson TypeToken? Jackson ObjectMapper.readValue怎么用泛型类,有人说需要JavaType,但是JavaType也在拼接其他类,Jackson可以像gson TypeToken一样使用吗?

my code is like this我的代码是这样的

    public static void main(String[] args) throws IOException {
    String json = "{\"code\":200,\"msg\":\"success\",\"reqId\":\"d1ef3b76e73b40379f895a3a7f1389e2\",\"cost\":819,\"result\":{\"taskId\":1103,\"taskName\":\"ei_custom_config\",\"jobId\":233455,\"status\":2,\"interrupt\":false,\"pass\":true}}";
    RestResponse<TaskResult> result = get(json);
    System.out.println(result);
    System.out.println(result.getResult().getJobId());
}

public static <T> RestResponse<T> get(String json) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(json, new TypeReference<RestResponse<T>>() {});
}

and error is错误是

org.example.zk.RestResponse@6fd02e5
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.example.zk.TaskResult
    at org.example.zk.JacksonTest.main(JacksonTest.java:15)

You need to provide jackson with concrete type information for T .您需要为杰克逊提供T的具体类型信息。 I would suggest using readValue() overload with parameter - JavaType .我建议使用带有参数的readValue()重载 - JavaType

Add the class of T as parameter of get() and construct parametric type using it.添加T的类作为get()的参数并使用它构造参数类型。

public static <T> RestResponse<T> get(String json, Class<T> classOfT) throws IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  JavaType type = TypeFactory.defaultInstance().constructParametricType(RestResponse.class, classOfT);
  return objectMapper.readValue(json, type);
}

Usage:用法:

RestResponse<TaskResult> result = get(json, TaskResult.class);

We can make T with upper-bound to help infering object type.我们可以使 T 具有上限以帮助推断对象类型。

public static <T extends TaskResult> RestResponse<T> get(String json) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(json, new TypeReference<RestResponse<T>>() {});
}

Without type bounduary, RestResponse<T> equals to RestResponse<Object>没有类型边界,RestResponse<T> 等于 RestResponse<Object>
We can not new a generic class with T.我们不能用 T 新建一个泛型类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM