首页 > 解决方案 > 如何在 DTO 模型中实现 JsonNode 类型的字段

问题描述

所以我有json文件,如:

{ "id" : 1,
   "includingJson" : {"foo" : "bar"}
}

我有一些 DTO,例如:

...
public class SubscriptionDTO extends AbstractDTO{
  private Long id;
  private JsonNode includingJson;

但是在我尝试通过代码将 JSON 转换为 POJO 之后

public static <T> T jsonStringToDto(Class<?> dtoClass, String jsonContent) {
  ObjectMapper mapper = new ObjectMapper();
  try {
    return (T) mapper.readValue(jsonContent, dtoClass);
  } catch (IOException e) {
    log.error(e);
  }
  return (T) new Object();
}

我收到错误消息Can not construct instance of org.codehaus.jackson.JsonNode, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information 所以主要问题 - 我该如何解决这个问题?

标签: javajackson

解决方案


看来您导入了错误的 JsonNode,它是较旧的。正确使用的类是com.fasterxml.jackson.databind.JsonNode,它可以工作。用杰克逊 2.8 对其进行了测试。此外,为了确保正常工作,最好 DTO 类具有 getter、setter 和无参数构造函数。所以,更新版本。


推荐阅读