【问题标题】:Java Jackson Polymorphic - Match on interface field results in duplicate field nameJava Jackson Polymorphic - 接口字段匹配导致重复的字段名称
【发布时间】:2020-01-10 02:19:20
【问题描述】:

我正在与杰克逊一起玩多态性。我有一个工作示例,但有一件事对我来说有点奇怪。生成 Json 时,我得到一个重复的字段。

我有以下树:花园 -> 动物 -> 狗或猫。

@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Garden {
    public String location;
    public Animal animal;
}


@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name", visible = true, defaultImpl = Dog.class)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "Dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "Cat")}
)
public interface Animal {
}

@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Cat implements Animal {
    public String name;
    public String nickname;
}

@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class Dog implements Animal {
    public String name;
    public String command;
}

程序:

public class App {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();

        Animal animal = new Dog("Dog", "Sit");
        Garden garden = new Garden("Utrecht", animal);

        try {
            String gardenJson = objectMapper.writeValueAsString(garden);

            System.out.println(gardenJson);

            Garden deserializedDog = objectMapper.readValue("{\"location\":\"Utrecht\",\"animal\":{\"name\":\"Dog\",\"command\":\"Sit\"}}", Garden.class);
            System.out.println("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当我从 Json 反序列化到 Java 时,一切都按预期运行(使用以下 Json:{"location":"Utrecht","animal":{"name":"Dog","command":"Sit" }})。但是在生成Json时:

{"location":"Utrecht","animal":{"name":"Dog","name":"Dog","command":"Sit"}}

如何摆脱重名属性?

【问题讨论】:

    标签: java serialization jackson polymorphism deserialization


    【解决方案1】:

    将 EXTERNAL_PROPERTY 替换为 EXISTING_PROPERTY。 所以你的示例行:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name", visible = true, defaultImpl = Dog.class)
    

    需要替换为:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "name", visible = true, defaultImpl = Dog.class)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2017-06-22
      • 2019-08-26
      • 2016-08-16
      相关资源
      最近更新 更多