Home / Companies / Speakeasy / Blog / Post Details
Content Deep Dive

Java Unions with Jackson: Discriminated, Non-Discriminated, and Primitives

Blog post from Speakeasy

Post Details
Company
Date Published
Author
Vishal Gowda
Word Count
2,202
Language
English
Hacker News Points
-
Summary

Vishal Gowda's article explores methodologies for handling evolving APIs in Java, focusing on implementing forward-compatible union types with Jackson. It discusses the challenges of maintaining backward compatibility when APIs introduce new types, emphasizing the importance of preserving unknown data to prevent crashes. Two primary patterns, discriminated and non-discriminated unions, are examined. Discriminated unions, suitable for object-only members, utilize a discriminator property within JSON objects to resolve types using Jackson annotations, while non-discriminated unions handle mixed member types via a custom deserializer, using a fallback mechanism to manage unknown data. The article highlights the limitations of Java interfaces and the advantages of using wrapper patterns for external types or primitives. It also touches on the enhancements Java 17+ brings, such as sealed interfaces and records, to simplify union handling. Additionally, the piece introduces Speakeasy, a tool for generating forward-compatible Java SDKs from OpenAPI specifications, which automates these patterns to ensure robust API interactions.