Ignore fields from Java object dynamically while sending as JSON from Spring MVC
Add the @JsonIgnoreProperties("fieldname")
annotation to your POJO.
Or you can use @JsonIgnore
before the name of the field you want to ignore while deserializing JSON. Example:
@JsonIgnore@JsonProperty(value = "user_password")public String getUserPassword() { return userPassword;}
I know I'm a bit late to the party, but I actually ran into this as well a few months back. All of the available solutions weren't very appealing to me (mixins? ugh!), so I ended up creating a new library to make this process cleaner. It's available here if anyone would like to try it out: https://github.com/monitorjbl/spring-json-view.
The basic usage is pretty simple, you use the JsonView
object in your controller methods like so:
import com.monitorjbl.json.JsonView;import static com.monitorjbl.json.Match.match;@RequestMapping(method = RequestMethod.GET, value = "/myObject")@ResponseBodypublic void getMyObjects() { //get a list of the objects List<MyObject> list = myObjectService.list(); //exclude expensive field JsonView.with(list).onClass(MyObject.class, match().exclude("contains"));}
You can also use it outside of Spring:
import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.module.SimpleModule;import static com.monitorjbl.json.Match.match;ObjectMapper mapper = new ObjectMapper();SimpleModule module = new SimpleModule();module.addSerializer(JsonView.class, new JsonViewSerializer());mapper.registerModule(module);mapper.writeValueAsString(JsonView.with(list) .onClass(MyObject.class, match() .exclude("contains")) .onClass(MySmallObject.class, match() .exclude("id"));
Can I do it dynamically?
Create view class:
public class View { static class Public { } static class ExtendedPublic extends Public { } static class Internal extends ExtendedPublic { }}
Annotate you model
@Documentpublic class User { @Id @JsonView(View.Public.class) private String id; @JsonView(View.Internal.class) private String email; @JsonView(View.Public.class) private String name; @JsonView(View.Public.class) private Instant createdAt = Instant.now(); // getters/setters}
Specify the view class in your controller
@RequestMapping("/user/{email}")public class UserController { private final UserRepository userRepository; @Autowired UserController(UserRepository userRepository) { this.userRepository = userRepository; } @RequestMapping(method = RequestMethod.GET) @JsonView(View.Internal.class) public @ResponseBody Optional<User> get(@PathVariable String email) { return userRepository.findByEmail(email); }}
Data example:
{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}