【发布时间】:2022-01-13 10:49:48
【问题描述】:
我尝试反序列化一个巨大的 API 负载。这个有效载荷包含的字段比我需要的多,因此我使用@JsonIgnoreProperties(ignoreUnknown = true)。但是在某些时候,反序列化失败并显示错误消息:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of FIELD_NAME token
at [Source: {
"objectEntries": [
{
"objectKey": "KDS-4300"
},
{
"objectKey": "KDS-4327"
}
]
}; line: 2, column: 3]
我找到了建议使用该案例的解决方案
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
我试过这个。但这并没有帮助。此外,我的结果数据不是单值数组。它实际上包含两个值 - 因此解决方案无论如何都不会加起来。
这是我作为反序列化目标的类。
@JsonIgnoreProperties(ignoreUnknown = true)
public class InsightQueryResult {
@JsonProperty("objectEntries")
private List<ObjectEntry> objectEntries;
@JsonCreator
public InsightQueryResult(List<ObjectEntry> objectEntries) {
this.objectEntries = objectEntries;
}
public List<ObjectEntry> getObjectEntries() {
return objectEntries;
}
// equals, hashCode and toString
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectEntry {
@JsonProperty("objectKey")
private String objectKey;
@JsonCreator
public ObjectEntry(String objectKey) {
this.objectKey = objectKey;
}
public String getObjectKey() {
return objectKey;
}
// equals, hashCode and toString
}
这是我测试它的单元测试:
@Test
public void shouldMapQueryResultToResultObject() throws IOException {
final Resource expectedQueryResult= new ClassPathResource("testQueryPayload.json");
final String expectedQueryResultData = new String(
Files.readAllBytes(expectedQueryResult.getFile().toPath())).trim();
final List<ObjectEntry> objectEntries = Arrays.asList(new ObjectEntry("KDS-4300"), new ObjectEntry("KD-4327"));
final InsightQueryResult expectedQueryResult = new InsightQueryResult(objectEntries);
final InsightQueryResult result = objectMapper.readValue(expectedQueryResultData, InsightQueryResult.class);
assertThat(result).isEqualTo(expectedQueryResult);
}
这是我要反序列化的有效负载
// testQueryPayload.json
{
"objectEntries": [
{
"objectKey": "KDS-4300"
},
{
"objectKey": "KDS-4327"
}
]
}
【问题讨论】: