DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Aggregating REST APIs Calls Using Apache Camel
  • How to Transform Any Type of Java Bean With BULL
  • Anemic Domain Model in Typical Spring Projects (Part 1)

Trending

  • Metrics at a Glance for Production Clusters
  • How to Perform Custom Error Handling With ANTLR
  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  1. DZone
  2. Coding
  3. Languages
  4. Spring Boot: Dynamically Ignore Fields While Serializing Java Objects to JSON

Spring Boot: Dynamically Ignore Fields While Serializing Java Objects to JSON

Learn how to ignore fields at runtime.

By 
Vicky AV user avatar
Vicky AV
·
Dec. 27, 20 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
28.9K Views

Join the DZone community and get the full member experience.

Join For Free

Let's say that we have a UserController class with two GET endpoints:

  • /users/{id} endpoint, which returns a User object for a given id
  • /users endpoint, which returns List<User>
Java
 




xxxxxxxxxx
1
26


 
1
public class User {
2

          
3
    private Integer id;
4
    private String name;
5
    private Date dateOfBirth;
6
    private String city;
7
    
8
    // constructors, getters & setters are ignored
9
}
10

          
11
@RestController
12
public class UserController {
13
    
14
    @Autowired
15
    UserService userService;
16
    
17
    @RequestMapping(value = "/user/{id}", method= RequestMethod.GET)
18
    User getUser(@PathVariable("id") String id){
19
        return userService.getUser(id);
20
    }
21
    
22
    @RequestMapping(value = "/users", method= RequestMethod.GET)
23
    List<User> getAllUsers(){
24
        return userService.getAllUsers();
25
    }
26
}



Our client wants the id and name of all users in a JSON List when the /users endpoint is called. For the /users/{id} endpoint, they want the name, dateOfBirth, and city for the given user id.

If we use the User POJO class for both the endpoints, we will get the id, name, dateOfBirth, and city all the time. So we have to figure out a way to ignore fields at the time of serialization.

The Jackson library provides two annotations: @JsonIgnore and @JsonIgnoreProperties to ignore fields while serializing Java Objects to JSON. But both these annotations need the fields at compile time itself.

But in our case, the fields to be ignored have to be decided at the runtime, based on the endpoint called.

However, we can use MappingJacksonValue to ignore fields dynamically.

Here is a sample implementation:

Java
 




x


 
1
public class User {
2

          
3
    private Integer id;
4
    private String name;
5
    private Date dateOfBirth;
6
    private String city;
7
    
8
    // constructors, getters & setters are ignored
9
}
10

          
11
@RestController
12
public class UserController {
13
    
14
     @Autowired
15
    UserService userService;
16
    
17
    @RequestMapping(value = "/user/{id}", method= RequestMethod.GET)
18
    MappingJacksonValue getUser(@PathVariable("id") String id){
19
        SimpleBeanPropertyFilter simpleBeanPropertyFilter =
20
                SimpleBeanPropertyFilter.serializeAllExcept("id");
21

          
22
        FilterProvider filterProvider = new SimpleFilterProvider()
23
                .addFilter("userFilter", simpleBeanPropertyFilter);
24

          
25
        User user = userService.getUser(id);
26
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(user);
27
        mappingJacksonValue.setFilters(filterProvider);
28

          
29
        return mappingJacksonValue;
30
    }
31
    
32
    @RequestMapping(value = "/users", method= RequestMethod.GET)
33
    MappingJacksonValue getAllUsers(){
34
         SimpleBeanPropertyFilter simpleBeanPropertyFilter =
35
                SimpleBeanPropertyFilter.serializeAllExcept("dateOfBirth", "city");
36

          
37
        FilterProvider filterProvider = new SimpleFilterProvider()
38
                .addFilter("userFilter", simpleBeanPropertyFilter);
39

          
40
        List<User> userList = userService.getAllUsers();
41
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
42
        mappingJacksonValue.setFilters(filterProvider);
43

          
44
        return mappingJacksonValue;
45
    }
46
}



Explanation:

  • Add the JsonFilter annotation on the POJO class

@JsonFilter("userFilter")

  • Pass the name of the fields to be ignored to the serializeAllExcept method from the SimpleBeanPropertyFilter class

SimpleBeanPropertyFilter.serializeAllExcept("dateOfBirth", "city") - will ignore dateOfBirth & city fields

  • Pass the JsonFilter name and SimpleBeanPropertyFilter object to the addFilter method

FilterProvider filterProvider = new SimpleFilterProvider().addFilter("userFilter", simpleBeanPropertyFilter);

  • Pass the instance of the POJO and filter class to the MappingJacksonValue class

MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);

mappingJacksonValue.setFilters(filterProvider);

  • Make sure MappingJacksonValue is the return type of the method

Now Spring will take care of ignoring the fields mentioned in SimpleBeanPropertyFilter on serialization.

That's all folks!

- @IamVickyAV

JSON Java (programming language) Object (computer science) Spring Framework

Published at DZone with permission of Vicky AV. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Check for JSON Insecure Deserialization (JID) Attacks With Java
  • Aggregating REST APIs Calls Using Apache Camel
  • How to Transform Any Type of Java Bean With BULL
  • Anemic Domain Model in Typical Spring Projects (Part 1)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!