Implementing Serialization/Deserialization

1. Implementing JSON Serialization

Example: Jackson ObjectMapper

ObjectMapper mapper = JsonMapper.builder()
    .addModule(new JavaTimeModule())
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    .serializationInclusion(JsonInclude.Include.NON_NULL)
    .build();
String json = mapper.writeValueAsString(order);
Order o = mapper.readValue(json, Order.class);

2. Implementing Custom Serializers

Example: Money serializer

public class MoneySerializer extends JsonSerializer<Money> {
    public void serialize(Money v, JsonGenerator g, SerializerProvider sp) throws IOException {
        g.writeStartObject();
        g.writeStringField("currency", v.currency().getCurrencyCode());
        g.writeNumberField("amount", v.amount());
        g.writeEndObject();
    }
}

3. Handling Date/Time Serialization

PracticeDetail
UTCAlways serialize in UTC
ISO-86012024-05-30T14:00:00Z
java.timeUse Instant, OffsetDateTime, LocalDate
Avoidjava.util.Date, timestamps in body

4. Handling Polymorphic Types

Example: Sealed + JsonTypeInfo

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = Card.class,    name = "card"),
  @JsonSubTypes.Type(value = BankXfer.class, name = "bank")
})
public sealed interface PaymentMethod permits Card, BankXfer {}

5. Implementing Deep Copy Logic

ApproachDetail
Records + immutablesNo copy needed
Copy constructorExplicit
Serialize/deserializeQuick deep clone via Jackson
LibraryMapStruct generates copy mappers

6. Implementing Field Filtering

MechanismDetail
@JsonIgnorePer-field exclusion
@JsonViewMultiple projections of same class
Filters@JsonFilter dynamic include/exclude
DTOsCleanest; explicit shape per use

7. Handling Null Values

SettingBehavior
ALWAYSInclude nulls
NON_NULLOmit nulls
NON_EMPTYOmit nulls + empty collections
NON_DEFAULTOmit defaults (0, false)

8. Implementing Versioned DTOs

StrategyDetail
Separate classesOrderV1Dto, OrderV2Dto
@JsonView per versionSingle class, multiple views
Mappersv1 ↔ v2 bidirectional

9. Handling Circular References

ApproachDetail
@JsonManagedReference / @JsonBackReferenceParent serialized, child back-ref omitted
@JsonIdentityInfoObject identity by ID
DTOsBreak cycles structurally
Warning: JPA entities frequently have lazy bidirectional relations — serialize DTOs, not entities.

10. Implementing Schema Validation

SpecUse
JSON SchemaValidate JSON shape
OpenAPIPer-endpoint schemas
Bean ValidationJVM-side post-bind
Avro/ProtobufCompile-time + runtime

11. Handling Binary Data

ApproachDetail
Base64 in JSON~33% overhead
Multipart uploadSeparate binary part
Pre-signed URLUpload directly to object store
ProtobufNative binary fields

12. Implementing Compression

CodecTrade-off
gzipUniversal, moderate
deflateSimilar to gzip
br (Brotli)Best ratio for text
zstdFast + great ratio
snappy/lz4Speed-focused (Kafka)