In Jackson I want to include type-information for every custom objects. To accomplish this without annotation, I am using
OBJECT_MAPPER.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, "@Ketan");
It is working but it is also including type-information for List
, Map
, Collection
like container itself.
Let me give you a standard example of Animal
, Dog
, Cat
and Zoo
hierarchy.
class Zoo {
List<Cat> cats;
Dog dog;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat> cats) {
this.cats = cats;
}
}
Here, I have two custom objects, Cat
and Dog
. I just want to include type information for only those, but it is including for container – List
in my case – as well.
Please see below the JSON string I got by serialization.
{
"@Ketan": "com.csam.wsc.enabling.core.codec.json.test.Zoo1",
"cats": [
// This line contains the issue //
"java.util.ArrayList",
[
{
"@Ketan": "com.csam.wsc.enabling.core.codec.json.test.Cat",
"name": "animalName",
"likesCream": true,
"lives": 10
},
{
"@Ketan": "com.csam.wsc.enabling.core.codec.json.test.Cat",
"name": "animalName",
"likesCream": true,
"lives": 10
}
]
],
"dog": {
"@Ketan": "com.csam.wsc.enabling.core.codec.json.test.Dog",
"name": "animalName",
"barkVolume": 0.0
}
}
Everything is fine to me except what I have highlighted – java.util.ArrayList
in the JSON string. I do not want such a container type information.
Is there any easy support at above API level itself to achieve this without overriding TypeResolverBuilder
or any customization?
If you extend the class ObjectMapper.DefaultTypeResolverBuilder
, it becomes quite easy though:
OBJECT_MAPPER.setDefaultTyping(new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL) {
{
init(JsonTypeInfo.Id.CLASS, null);
inclusion(JsonTypeInfo.As.PROPERTY);
typeProperty("@Ketan");
}
@Override
public boolean useForType(JavaType t) {
return !t.isContainerType() && super.useForType(t);
}
});
不可以,除非您声明集合为最终类型。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.