0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.