Home > Java > javaTutorial > body text

How Can I Selectively Exclude Fields from JSON Serialization Without Affecting Deserialization?

DDD
Release: 2024-11-24 13:28:12
Original
516 people have browsed it

How Can I Selectively Exclude Fields from JSON Serialization Without Affecting Deserialization?

Selective Application of @JsonIgnore: Addressing Serialization-only Exclusion

During data exchange with a server, a user object may contain sensitive information that should be hidden from clients during serialization. An approach often used is applying the @JsonIgnore annotation to conceal sensitive properties. However, this can also interfere with deserialization, creating challenges in specific scenarios.

Understanding the Issue

The @JsonIgnore annotation on a property prevents its inclusion in JSON serialization. However, if the same property is needed during deserialization (e.g., to create a user account), the exclusion becomes problematic.

Selective Exclusion with @JsonIgnore

To resolve this issue, two different approaches can be taken depending on the version of Jackson used:

Jackson versions prior to 1.9:

  • Using @JsonIgnore on the Getter: Annotating only the getter method allows the property to be included during deserialization and excluded during serialization.

Jackson versions 1.9 and later:

  • @JsonProperty with READ_ONLY: By adding the annotation arguments @JsonProperty(access = JsonProperty.Access.READ_ONLY) to the setter, you can specify that the property is only writable and excluded during serialization.

Example:

Consider a user object with a password field:

@JsonIgnore
private String password;

// Setter with READ_ONLY access (Jackson 1.9 and later)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public void setPassword(String password) {
    this.password = password;
}
Copy after login

Note:

  • Using READ_ONLY ensures that the password is only used for deserialization.
  • Both approaches have been verified and function as intended.

The above is the detailed content of How Can I Selectively Exclude Fields from JSON Serialization Without Affecting Deserialization?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template