Reputation: 11164
I have a spring boot endpoint that returns a list of users. The users are populated into a DTO called User
, however, some attributes of the user can be empty. Therefore how can I not send the empty attributes to the frontend?
@RequestMapping(value = "/users", produces = {"application/json"}, method = RequestMethod.GET)
public List<User> getAllUsers() throws IOException {
return kcAdminClient.getAllUsers();
}
public class User {
private String firstName;
private String lastName;
private String password;
private String email;
private String contactNumber;
private String address;
private String[] roles;
}
public List<User> getAllUsers() {
int count = usersResource.count();
List<User> userList = new ArrayList<>();
List<UserRepresentation> userRepresentationList = usersResource.list();;
for (UserRepresentation ur : userRepresentationList) {
User user = new User();
user.setEmail(ur.getEmail());
user.setFirstName(ur.getFirstName());
user.setLastName(ur.getLastName());
userList.add(user);
}
return userList;
}
Returned values
{
"firstName": "test",
"lastName": "test",
"password": null,
"email": "[email protected]",
"contactNumber": null,
"address": null,
"roles": [
"test"
]
}
How can I stop the password and roles attribute from being sent as null?
Thanks in Advance
Upvotes: 0
Views: 2104
Reputation: 2817
Beside @Saurabh answer, and if you want to apply this behaviour globally across your application you can simply add this to your application.properties
:
spring.jackson.default-property-inclusion = non_null
For more objectMapper tunning you can check Spring Boot Documentation > How To Customize The Jackson ObjectMapper
Upvotes: 1
Reputation: 943
You can use @JsonInclude(Include.NON_NULL)
at the class level so your code would be like below,
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class User {
private String firstName;
private String lastName;
private String password;
private String email;
private String contactNumber;
private String address;
private String[] roles;
}
This will ignore null
values. For more info please visit this.
Upvotes: 2