Search code examples
javajsonspringspring-mvcmodel

I want to ignore fields from JSON only in few cases is it possible?


My ModelClass

public class UserPojo{

   private String userEmailId;
   private String userPassword;
   private String userContactNumber;
   //setters and getters
}

I want to send UserPojo class object as json but In somecases I want to send with userpassword and somecases without userpassword is it possible?

In below method I want to send userPojo object without userpassword. My Spring version is 4.3.1.RELEASE. I have Jackson libraries

@RestController
@RequestMapping("/user")
public class UserController{

 @GetMapping(value="/{userId}")
 public UserPojo getUser(@PathVariable("userId") String userId){

   //code goes here 
   //finally returning UserPojo Object
   return userPojo;
 }   

}

In below method I want to send userPojo object with password

@RestController
@RequestMapping("/admin")
public class AdminController{

 @GetMapping(value="/{userId}")
 public UserPojo getUser(@PathVariable("userId") String userId){

   //code goes here 
   //finally returning UserPojo Object
   return userPojo;
 }   

}

I hope you got my point


Solution

  • For your requirement use @JsonView, if you want to ignore totally some field then @JsonIgnore.