1
0

Part 4: mix-ins registered on the builder

This commit is contained in:
2026-08-04 17:31:59 +00:00
parent 1f6f6fd855
commit 3e7cea3f2a

View File

@@ -0,0 +1,48 @@
package com.ankurm.jackson3.part4custom;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import tools.jackson.databind.json.JsonMapper;
/**
* Post: Custom Serialisers and Mix-ins — https://ankurm.com/jackson-custom-serializer-mixin/
* Section: "Mix-in Annotations — Annotating Third-Party Classes"
*
* Jackson 3 difference: mixins are registered on the BUILDER (addMixIn), because
* mapper.addMixIn(...) does not exist on an immutable mapper.
*/
public class E04MixinAnnotations {
/** Stand-in for a third-party class whose source you cannot modify. */
public static class Address {
public String street;
public String city;
public String postalCode;
public String internalTrackingCode; // must never reach the wire
}
/** Mix-in: carries the annotations Jackson should apply to Address. */
public abstract static class AddressMixin {
@JsonIgnore public String internalTrackingCode; // suppress
@JsonProperty("zip") public String postalCode; // rename
}
public static void main(String[] args) {
JsonMapper mapper = JsonMapper.builder()
.addMixIn(Address.class, AddressMixin.class)
.build();
Address address = new Address();
address.street = "123 Main St";
address.city = "Springfield";
address.postalCode = "12345";
address.internalTrackingCode = "INTERNAL-X99";
System.out.println("with mixin : " + mapper.writeValueAsString(address));
// The target class is untouched — a mapper without the mixin still sees
// every field under its original name.
System.out.println("without mixin: "
+ JsonMapper.builder().build().writeValueAsString(address));
}
}