没有为集合中的对象编写JsonTypeInfo

时间:2019-03-18 11:35:23

标签: java jackson

我正在尝试使用Jackson 2.9.8对多态类型进行序列化/反序列化,除非我将这种类型的对象放入集合中,否则它可以正常工作,因为由于某种原因类型信息不是然后写。让我们考虑以下示例:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "animalKind")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "Dog")
})
public interface Animal {
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dog implements Animal {
    private Boolean goodBoy;
    public Boolean isGoodBoy() { return goodBoy; }
    public void setGoodBoy(Boolean goodBoy) { this.goodBoy = goodBoy; } 
}

现在让我们序列化Dog的实例:

ObjectMapper objectMapper = new ObjectMapper();

Dog mike = new Dog();
mike.setGoodBoy(true);

// This works just fine
String mikeJson = objectMapper.writeValueAsString(mike);
System.out.println(mikeJson);

// This doesn't work
String listJson = objectMapper.writeValueAsString(Collections.singleton(mike));
System.out.println(listJson);

// This doesn't either
String mapJson = objectMapper.writeValueAsString(Collections.singletonMap("Mike", mike));
System.out.println(mapJson);

输出如下:

{"animalKind":"Dog","goodBoy":true}
[{"goodBoy":true}]
{"Mike":{"goodBoy":true}}

因此,animalKind是用第一种情况写的,但不是用第二种和第三种情况写的。我在这里缺少一些序列化设置还是一个错误?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要通过阅读抽象类型注释来指示Jackson您需要给定的集合。参见示例:

CollectionType animalsListType = mapper.getTypeFactory()
    .constructCollectionType(Set.class, Animal.class);
System.out.println(mapper.writer().withType(animalsListType).writeValueAsString(Collections.singleton(mike)));

Map<String, Dog> mikeMap = Collections.singletonMap("Mike", mike);
MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Animal.class);
System.out.println(mapper.writer().withType(mapType).writeValueAsString(mikeMap));

上面的代码显示:

[{"animalKind":"Dog","goodBoy":true}]
{"Mike":{"animalKind":"Dog","goodBoy":true}}