Java JSON processing guide: Jackson ObjectMapper, annotations, custom serializers, polymorphism, Gson comparison, and common pitfalls.
JSON Processing: Jackson and Gson
JSON is the lingua franca of web APIs. Java does not include a built-in JSON library, so you need either Jackson (the de facto standard) or Gson (Google's lighter alternative). This page focuses on Jackson with a Gson comparison at the end.
Jackson setup
Maven dependency:
ObjectMapper basics
ObjectMapper is the central class. Reuse a single instance - it is thread-safe
and expensive to create.
Serialisation (Java to JSON)
Deserialisation (JSON to Java)
Deserialising generic types
ObjectMapper configuration
Common modules
Annotations
Field-level annotations
Class-level annotations
@JsonCreator for custom construction
Custom serialisers and deserialisers
Custom serialiser
Custom deserialiser
Polymorphism
When a JSON field can contain different subtypes, use @JsonTypeInfo:
Working with JSON trees
When you don't have (or want) a POJO:
Gson comparison
Setup
Basic usage
Jackson vs Gson
Recommendation: Use Jackson for server-side Java (it is the Spring default and has the richest feature set). Use Gson if you need a smaller footprint or are on Android.