0

I'm writing a dto class containing the information of a user

public class User {
    private String firstName;
    
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

I'd receive this JSON object if I do GET api/v1/user/1

{
  firstName: John,
  lastName: Kennedy
}

But when the firstName and the lastName are null, I want to receive an empty object like:

{}

How would you do technically on Spring Boot in order to receive such empty object in Json format?

Thank you in advance

2 Answers 2

5

You could try to annotate your class with:

@JsonInclude(Include.NON_NULL)
Sign up to request clarification or add additional context in comments.

Comments

0

If you want an empty object { } and empty request is not valid for you, you can create an auxiliar class called EmptyObject or something similar:

@JsonSerialize
public class EmptyObject {

}

And into your controller:

return user.getFirstName() == null && user.getLastName() == null ?  
                ResponseEntity.ok(new EmptyObject()) : ResponseEntity.ok(user);

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.