没有为集合中的对象编写JsonTypeInfo [英] JsonTypeInfo not written for an object in a collection

查看:109
本文介绍了没有为集合中的对象编写JsonTypeInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jackson 2.9.8对多态类型进行序列化/反序列化,并且除非我将这种类型的对象放入集合中,否则它会很好地工作,因为出于某种原因,当时不会写入类型信息.让我们考虑以下示例:

I'm trying to serialize/deserialize a polymorphic type with Jackson 2.9.8, and it works fine unless I put an object of such type into a collection, because for some reason type info is not written then. Let's consider the following example:

@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的实例:

Now let's serialize an instance of 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是在第一种情况下写的,但不是在第二种和第三种情况下写的.我在这里缺少一些序列化设置还是一个错误?

So the animalKind is written in the first case but it's not in the second and the third case. Am I missing some serialization settings here or is it a bug?

谢谢!

推荐答案

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

You need to instruct Jackson that you need given collection with reading abstract type annotation. See example:

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}}

这篇关于没有为集合中的对象编写JsonTypeInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆