簡體   English   中英

傑克遜desearlization:根源上的兩個鍵。 我怎么解開一個而忽略另一個?

[英]jackson desearlization: two keys at root. how do i unwrap one and ignore the other?

使用傑克遜2.x.

json響應如下所示:

{
 "flag": true,
 "important": {
   "id": 123,
   "email": "foo@foo.com"
 }
}

“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 }
}

當我嘗試將@JsonRootName(“important”)添加到Important並使用DeserializationFeature.UNWRAP_ROOT_VALUE配置ObjectMapper時,我收到一個JsonMappingException:

根名稱'flag'與類型的預期('important')不匹配...

當我從JSON中刪除“flag”鍵/值時,數據綁定工作正常。 如果我將@JsonIgnoreProperties(“flag”)添加到Important中,我會得到相同的結果。

更新


更新的類...實際上將通過編譯步驟

@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());
}

實際測試:

 @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()); } 

結果:

com.fasterxml.jackson.databind.JsonMappingException:根名稱'flag'與type [simple type,class TestImportant $ Important]的expected('important')不匹配

僅僅因為Jackson中JSON解析的流媒體性質,我擔心沒有簡單的方法來處理這種情況。

從我的角度來看,使用某種包裝器更容易。

考慮以下代碼:

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

    public Important getImportant() {
        return important;
    }
}

而實際測試:

@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());
}

注意, @JsonRootName("important")是多余的,在這種情況下可以刪除。

這看起來有些丑陋,但只需相對較小的努力即可完美運作。 此類“包裝”也可以通用,但這更像是建築的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM