Home >Java >javaTutorial >How to Exclude Fields from Java Objects When Sending JSON in Spring MVC?

How to Exclude Fields from Java Objects When Sending JSON in Spring MVC?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 00:49:02571browse

How to Exclude Fields from Java Objects When Sending JSON in Spring MVC?

Ignoring Fields from Java Objects When Sending JSON from Spring MVC

In Spring MVC applications, it is often desirable to selectively exclude certain fields from Java objects when sending them as JSON responses. This ensures that only the necessary information is shared with clients, enhancing data privacy and reducing bandwidth consumption.

Problem Statement

In the provided code, the User model class has fields for createdBy, updatedBy, and encryptedPwd. However, the requirement is to dynamically ignore these fields while sending the JSON response.

Solution

There are two ways to exclude fields dynamically using annotations:

1. Using @JsonIgnoreProperties("fieldname"):

Annotate the User class with @JsonIgnoreProperties("fieldname"), specifying the fields that should be excluded. For example:

<code class="java">@JsonIgnoreProperties(value = {"createdBy", "updatedBy", "encryptedPwd"})
public class User {
    // ... (Class definition remains the same)
}</code>

2. Using @JsonIgnore on Individual Fields:

Annotate specific fields with @JsonIgnore before the field declaration. For example:

<code class="java">public class User {
    private Integer userId;
    private String userName;
    
    @JsonIgnore
    private String encryptedPwd;
    
    // ... (Other fields remain the same)
}</code>

Note: @JsonIgnore is the recommended approach as it provides more granular control over which fields are excluded.

GitHub Example

For a practical implementation, refer to the following GitHub example: https://github.com/FasterXML/jackson-databind/issues/1416

The above is the detailed content of How to Exclude Fields from Java Objects When Sending JSON in Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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