有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javacom。fasterxml。杰克逊。数据绑定。exc.InvalidDefinitionException:没有为ObjectReader配置值类型

我在执行下面的代码时收到com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No value type configured for ObjectReader问题

杰克逊的版本是jackson-databind-2.9.9.jar

public <T> T parsingData(String body) {
  try {
    return getObjectMapper().reader().readValue(body);
  } catch (IOException ioe) {
     ioe.printStackTrace();
  }
}

下面是确切的异常,我进入printStackTrace,可以找到异常中公开的String body

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No value type configured for ObjectReader
at [Source: (String)"{
     "timestamp": "2019-06-04T09:36:50.086+02:00",
     "path": "/api/check/85358/checking/246syb-f3f2-4756-91da-dae3e8ce774b/test/22462da-c4e2-45ca-bd27-246/rows/8bc3965a-ae22-4d7f-b770-262sgs24/port",
     "status": 400,
     "error": "Internal Server Error",
     "message": "[owner.firstName2:size:1:30, owner.lastName2:size:1:30]",
     "errorCode": 200000
    }
    "; line: 1, column: 1]

更新:您能解释一下我为什么会收到此异常吗?这是因为我没有提供Class还是TypeReference


共 (1) 个答案

  1. # 1 楼答案

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No value type configured for ObjectReader

    意味着,Jackson不知道要反序列化到哪种类型。由于Type Erasure in Java,它无法工作

    当您绑定一个类时,它将起作用:

    public static <T> T parsingData(String body) throws IOException {
        return new ObjectMapper().readerFor(A.class).readValue(body);
    }
    

    或使用Class参数:

    public static <T> T parsingData(String body, Class<T> clazz) throws IOException {
        return new ObjectMapper().readerFor(clazz).readValue(body);
    }
    

    参见readValue方法的类似问题以及如何解决:How do I parametrize response parsing in Java?

    为了理解readValue方法,我们需要看看documentation

    Method that binds content read from given JSON string, using configuration of this reader. Value return is either newly constructed, or root value that was specified with withValueToUpdate(Object).

    但在您的代码中,您使用的是纯阅读器,没有任何配置

    如果您不知道某个类型,只需将JSON反序列化为JsonNode,这可能是最通用的方式:

    JsonNode root = new ObjectMapper().readTree(json);