Java Jackson多态性--接口字段的匹配导致重复的字段名。

问题描述 投票:0回答:1

我在玩多态性与杰克逊的结合。我有一个工作实例,但有一件事对我来说有点奇怪。当生成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个回答
0
投票

用EXISTING_PROPERTY替换EXTERNAL_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)
© www.soinside.com 2019 - 2024. All rights reserved.