Part 3: @JsonProperty and @JsonIgnore, both directions
This commit is contained in:
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ankurm.jackson3.part3annotations;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||||
|
* Sections: "@JsonProperty" and "@JsonIgnore"
|
||||||
|
*
|
||||||
|
* Every @Json* annotation is imported from com.fasterxml.jackson.annotation, even
|
||||||
|
* on Jackson 3. jackson-annotations deliberately keeps the old group ID and package
|
||||||
|
* so one copy can be shared by Jackson 2 and Jackson 3 code on the same classpath.
|
||||||
|
*/
|
||||||
|
public class D01RenameAndIgnore {
|
||||||
|
|
||||||
|
public record OrderSummary(
|
||||||
|
@JsonProperty("order_id") Long orderId,
|
||||||
|
@JsonProperty("customer_name") String customerName) { }
|
||||||
|
|
||||||
|
public record UserAccount(
|
||||||
|
String username,
|
||||||
|
@JsonIgnore String passwordHash) { }
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
JsonMapper mapper = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
System.out.println("rename : "
|
||||||
|
+ mapper.writeValueAsString(new OrderSummary(1001L, "Alice")));
|
||||||
|
|
||||||
|
// Deserialisation honours the renamed key in both directions.
|
||||||
|
OrderSummary back = mapper.readValue(
|
||||||
|
"{\"order_id\":1001,\"customer_name\":\"Alice\"}", OrderSummary.class);
|
||||||
|
System.out.println("read back : " + back);
|
||||||
|
|
||||||
|
System.out.println("ignore : "
|
||||||
|
+ mapper.writeValueAsString(new UserAccount("alice", "$2a$10$secret")));
|
||||||
|
|
||||||
|
// @JsonIgnore is bidirectional: the field is not read from JSON either.
|
||||||
|
UserAccount ignored = mapper.readValue(
|
||||||
|
"{\"username\":\"alice\",\"passwordHash\":\"injected\"}", UserAccount.class);
|
||||||
|
System.out.println("read back : passwordHash=" + ignored.passwordHash());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user