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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory

Trending

  • Agentic Systems and Design Patterns
  • Building a Software Factory With AI Agents and Workflows
  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • When One Docker Swarm Replica Became Unreachable Over an Overlay Network: A Production Case With Traefik

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Dec. 27, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
30.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook