Ren*_*hek 3 java jackson jackson-databind
我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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我进入的确切异常之下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]
Run Code Online (Sandbox Code Playgroud)
更新:你能解释一下为什么我会收到这个异常吗?这是因为我没有提供Class还是TypeReference?
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No value type configured for ObjectReader
Means, Jackson does not know which type you would like to deserialise to. It does not work because of Type Erasure in Java.
It will work when you bind a class:
public static <T> T parsingData(String body) throws IOException {
return new ObjectMapper().readerFor(A.class).readValue(body);
}
Run Code Online (Sandbox Code Playgroud)
Or with Class param:
public static <T> T parsingData(String body, Class<T> clazz) throws IOException {
return new ObjectMapper().readerFor(clazz).readValue(body);
}
Run Code Online (Sandbox Code Playgroud)
See similar question for readValue method and how it could be solved: How do I parametrize response parsing in Java?
To understand readValue mehtod we need to take a look on 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).
but in your code you used pure reader without any configuration.
如果您不知道一种类型,只需将其反序列化JSON,JsonNode这可能是最通用的方式:
JsonNode root = new ObjectMapper().readTree(json);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2162 次 |
| 最近记录: |