我在玩多态性与杰克逊的结合。我有一个工作实例,但有一件事对我来说有点奇怪。当生成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"}}
如何去掉重复的名字属性?
用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)