我正在和杰克逊一起玩多态。我有一个可行的示例,但对我来说有点奇怪。生成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"}}
如何摆脱重复的name属性?
答案 0 :(得分:0)
将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)