Hải Trung Phạm
Hải Trung Phạm

Reputation: 89

Return an empty object Java Spring Boot REST

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

Upvotes: 0

Views: 3063

Answers (2)

J.F.
J.F.

Reputation: 15187

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);

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 9650

You could try to annotate your class with:

@JsonInclude(Include.NON_NULL)

Upvotes: 5

Related Questions