jackson desearlization:根有两个键。我如何打开一个并忽略另一个?

car*_*los 5 java json jackson

使用杰克逊 2.x

json 响应如下所示:

{
 "flag": true,
 "important": {
   "id": 123,
   "email": "foo@foo.com"
 }
}
Run Code Online (Sandbox Code Playgroud)

“flag”键不提供任何有用的信息。我想忽略“标志”键并将“重要”值解包到重要的实例。

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 }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将 @JsonRootName("important") 添加到重要并使用 DeserializationFeature.UNWRAP_ROOT_VALUE 配置 ObjectMapper 时,我收到一个 JsonMappingException:

根名称“标志”与类型的预期(“重要”)不匹配...

当我从 JSON 中删除“标志”键/值时,数据绑定工作得很好。如果我也将 @JsonIgnoreProperties("flag") 添加到重要,我会得到相同的结果。

更新


更新的类......实际上会通过编译步骤

@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; }
}
Run Code Online (Sandbox Code Playgroud)

实际测试:

@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("foo@foo.com", important.getEmail());
}
Run Code Online (Sandbox Code Playgroud)

结果:

com.fasterxml.jackson.databind.JsonMappingException:根名称“标志”与类型 [简单类型,类 TestImportant$Important] 的预期(“重要”)不匹配

n1c*_*las 2

由于 Jackson 中 JSON 解析的流式性质,恐怕没有简单的方法来处理此类情况。

从我的角度来看,使用某种包装器更容易做到。

考虑这段代码:

public static class ImportantWrapper {
    @JsonProperty("important")
    private Important important;

    public Important getImportant() {
        return important;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及实际测试:

@Test
public void deserializeImportant() throws IOException {
    ObjectMapper om = new ObjectMapper();
    //note: this has to be present
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Important important = om.readValue(getClass().getResourceAsStream("/important.json"), ImportantWrapper.class)
                                .getImportant();

    assertEquals((Integer)123, important.getId());
    assertEquals("foo@foo.com", important.getEmail());
}
Run Code Online (Sandbox Code Playgroud)

请注意,这@JsonRootName("important")是多余的,在这种情况下可以删除。

这看起来有些丑陋,但只需相对较小的努力就可以完美地工作。这样的“包装器”也可以被泛化,但这更像是建筑的东西。