我目前正在嘗試使用能夠處理多態(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屬性。
添加回答
舉報(bào)
0/150
提交
取消