使用杰克逊 2.x
json 响应如下所示:
{
"flag": true,
"important": {
"id": 123,
"email": "[email protected] /cdn-cgi/l/email-protection"
}
}
“flag”键不提供任何有用的信息。我想忽略“flag”键并将“important”值解包到“Important”的实例中。
public class Important {
private Integer id;
private String email;
public Important(@JsonProperty("id") Integer id,
@JsonProperty("email") String email) {
this.id = id;
this.email = email;
}
public String getEmail() { this.email }
public Integer getId() { this.id }
}
当我尝试将 @JsonRootName("important") 添加到重要并使用 DeserializationFeature.UNWRAP_ROOT_VALUE 配置 ObjectMapper 时,我收到 JsonMappingException:
根名称“标志”与类型的预期(“重要”)不匹配...
当我从 JSON 中删除“标志”键/值时,数据绑定工作得很好。如果我也将 @JsonIgnoreProperties("flag") 添加到“重要”,我会得到相同的结果。
UPDATES
updated class ... that will actually pass the compile step
@JsonRootName("important")
public static class Important {
private Integer id;
private String email;
@JsonCreator
public Important(@JsonProperty("id") Integer id,
@JsonProperty("email") String email) {
this.id = id;
this.email = email;
}
public String getEmail() { return this.email; }
public Integer getId() { return this.id; }
}
实际测试:
@Test
public void deserializeImportant() throws IOException {
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Important important = om.readValue(getClass().getResourceAsStream("/important.json"), Important.class);
assertEquals((Integer)123, important.getId());
assertEquals("[email protected] /cdn-cgi/l/email-protection", important.getEmail());
}
results:
com.fasterxml.jackson.databind.JsonMappingException:根名称“flag”与类型[简单类型,类 TestImportant$Important] 的预期(“重要”)不匹配