Reputation: 89
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
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
Reputation: 9650
You could try to annotate your class with:
@JsonInclude(Include.NON_NULL)
Upvotes: 5