cloudevents / cloudevents/sdk-java
Polymorphic JSON deserialization with Jackson
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 446
- Forks
- 172
- PR merge metrics
- No merged PRs in 30d
Description
I was wondering how to write a polymorphic parser for JSON CloudEvents, where the payload can be one of many types.
Normally, with plain Jackson one can do something like this, using @JsonTypeInfo and a type field somewhere in the JSON to determine the specific class for deserialization.
In this simple example in the CloudEvent SDK docs we knew the type in advance:
PojoCloudEventData<User> cloudEventData = mapData(
inputEvent,
PojoCloudEventDataMapper.from(objectMapper,User.class)
);
But in my case, I would like to achieve something like the following:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Foo.class, name = "foo"),
@JsonSubTypes.Type(value = Bar.class, name = "bar")
})
sealed interface Payload permits Foo, Bar {}
record Foo(String str) implements Payload {}
record Bar(int i) implements Payload {}
// ...
PojoCloudEventData<Payload> cloudEventData = mapData(
inputEvent,
PojoCloudEventDataMapper.from(objectMapper, Payload.class)
);
Running this code, it results in an error (as expected):
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class Payload]: missing type id property 'type'
Because the type field is part of the CloudEvent header and/or envelope that Jackson does not know about at this point.
What's your take on this?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the SDK Java JSON-Jackson documentation and the mapData and PojoCloudEventDataMapper usage shown in the issue, then compare them with Jackson's @JsonTypeInfo and @JsonSubTypes approach. Done would be a documented or implemented way to resolve polymorphic payload types from the CloudEvent envelope, with the supported behavior and limitations made clear.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java, json
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100