Reputation: 1789
I am currently working in a project where I have a User model and am using a REST API to fetch a list of users. (I have more entities.)
User has a password field. I do not want to include the password field in the result. So I excluded it in the DTO. But when I want to create a User, I want to include the password in the request. So Spring MVC gets the User entity (not the DTO).
I don't think it is good to do so.... For example, I have Event model which is connected to user with a many-to-many relationship. I don't want that in the request. I want only the user. So what do you suggest me to do? Have another kind-of DTO?
Upvotes: 6
Views: 20485
Reputation: 5525
I'm tried this JsonProperty.Access.WRITE_ONLY
and it's working with me.
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
Upvotes: 1
Reputation: 469
To avoid using @JsonIgnore, you can use json-view library. For example, in your controller you can do something like this:
At first, declare this in your controller variable:
private JsonResult json = JsonResult.instance();
And then use this method:
@RequestMapping("/get/{id}")
public void getUserById(@PathVariable(value = "id") long id) {
User user = usersService.findOne(id);
json.use(JsonView.with(user)
.onClass(User.class, Match.match()
.exclude("password").exclude("yetAnothertopSecretField")));
}
It returns JSON without excluded fields.
The JsonView and JsonResult classes are imported from the json-view library.
Upvotes: 6
Reputation: 2447
Use @JsonIgnore
with Access.WRITE_ONLY
for getter methods only.
Example
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
Upvotes: 31
Reputation: 145
If you are using Jackson to serialize your response objects, you can annotate the property in question with @JsonIgnore and it will not be included in the response.
public User {
private String email;
@JsonIgnore
private String password
...getters and setters
}
It might also be a good idea to create separate response objects that only include the fields you want in case you add sensitive fields down the road and forget to hide them. Likewise, you would also have separate request objects for creating users that would include a password field. Business entities, like a User, are probably best to use only internally, so you can control what information goes public.
Upvotes: 8
Reputation: 5950
Make the field 'password' as null while sending the response and Jackson will not show that in response. Don't remove it completely from the model class.
Upvotes: -2