第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Jackson:繼承和必需的屬性

Jackson:繼承和必需的屬性

藍(lán)山帝景 2021-04-05 20:16:47
我目前正在嘗試使用能夠處理多態(tài)性的杰克遜(Jackson)實(shí)現(xiàn)反序列化器,也就是說,給定這兩個(gè)類:public abstract class Animal {  private String name;  private float weight;  @JsonCreator  protected Animal(@JsonProperty(value="name") String name, @JsonProperty(value="weight",required=true) int weight) {      this.name=name;      this.weight=weight;  }}public class Dog extends Animal {    private int barkVolume;    @JsonCreator    public Dog(String name,int weight, @JsonProperty(value="barkVolume",required=true) int barkVolume) {        super(name, weight);        this.barkVolume=barkVolume;    }}解串器應(yīng)該能夠從json字符串中推斷并實(shí)例化適當(dāng)?shù)淖宇?。我使用了一個(gè)自定義的反序列化器模塊,UniquePropertyPolymorphicDeserializer(來自https://gist.github.com/robinhowlett/ce45e575197060b8392d)。該模塊的配置如下:UniquePropertyPolymorphicDeserializer<Animal> deserializer =             new UniquePropertyPolymorphicDeserializer<Animal>(Animal.class);        deserializer.register("barkVolume", Dog.class);        SimpleModule module = new SimpleModule("UniquePropertyPolymorphicDeserializer");        module.addDeserializer(Animal.class, deserializer);        mapper.registerModule(module);該模塊向用戶詢問Animal的每個(gè)子類的唯一屬性。因此,當(dāng)反序列化程序找到具有barkVolume屬性的json字符串時(shí),它知道應(yīng)該實(shí)例化Dog。但是,我對(duì)json屬性的規(guī)范存在疑問,因?yàn)樽宇惒荒軓母割愔薪o定的屬性繼承。在Dog類中,我必須再次指定“ name”和“ weight”是json屬性,即使在Animal類中已經(jīng)指定了這些屬性:public Dog(@JsonProperty(value="name") String name, @JsonProperty(value="weight",required=true) int weight, @JsonProperty(value="barkVolume",required=true) int barkVolume) {        super(name, weight);        this.barkVolume=barkVolume;    }否則,解串器將產(chǎn)生錯(cuò)誤:com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid type definition for type `Animals.Dog`: Argument #0 has no property name, is not Injectable: can not use as Creator [constructor for Animals.Dog, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] at [Source: UNKNOWN; line: -1, column: -1]這個(gè)解決方案對(duì)我來說并不令人滿意:每次我們要?jiǎng)?chuàng)建Animal的新子類時(shí),都必須在此類中指定name和weight為json屬性。
查看完整描述

1 回答

?
眼眸繁星

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊

我最終決定創(chuàng)建自己的Deserializer(而不是UniquePropertyDeserializer),在其中使用自省功能獲取父類的字段。它允許避免在子類中再次指定所需的json屬性。


查看完整回答
1 反對(duì) 回復(fù) 2021-04-28
  • 1 回答
  • 0 關(guān)注
  • 384 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)