https://github.com/phxql/jackson-polymorphic-deserialization
Small showcase for Jacksons polymorphic deserialization feature
https://github.com/phxql/jackson-polymorphic-deserialization
Last synced: 12 months ago
JSON representation
Small showcase for Jacksons polymorphic deserialization feature
- Host: GitHub
- URL: https://github.com/phxql/jackson-polymorphic-deserialization
- Owner: phxql
- Created: 2019-12-05T13:46:27.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2023-04-02T10:57:25.000Z (over 3 years ago)
- Last Synced: 2025-04-25T18:39:27.356Z (about 1 year ago)
- Language: Java
- Size: 58.6 KB
- Stars: 4
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Jackson's Polymorphic Deserialization
This repo contains an abstract class `Animal`, which has two subtypes: `Cat` (with a boolean flag `canMeow`) and a `Dog`
(with a boolean flag `canBark`).
Serializing an object of `Cat` or `Dog` is no problem, because Jackson can find out the actual class at runtime. Problems
start when trying to deserialize the JSON.
Well,
```
Cat cat2 = mapper.readValue(catJson, Cat.class);
```
works, because of the `Cat.class` in the method call. But what if you want to read a JSON, which could contain a `Dog` or
a `Cat`?
```
Animal dog2 = mapper.readValue(dogJson, Animal.class);
```
For that you can use `@JsonTypeInfo`. Take a look at the [Animal class](src/main/java/de/mkammerer/jpd/Animal.java).
The JSON result looks like this:
```json
{
"type" : "cat",
"name" : "Ms. Cat",
"canMeow" : true
}
```
```json
{
"type" : "dog",
"name" : "Mr. Dog",
"canBark" : true
}
```