Reputation: 10872
I'm using Jersey and Jackson to build a web application. Responses will be returned by using logic similar to the code snippets below. (unrelated parts are deleted)
public Response toResponse() {
String name = // some methods to get name
Integer score = // some methods to get score
final MyDTO dto = new MyDTO(name, score);
return Response
.ok()
.encoding(StandardCharsets.UTF_8.toString())
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(dto)
.build();
}
And the MyDTO
class:
@XmlRootElement
public final class MyDTO {
@NotNull final private String name;
@NotNull final private Integer score;
// constructor, getters, setters...
}
And I'm allowed to have only non-null values in MyDTO.
What I want to achieve is to hide score
field in the JSON response when the score
exactly equals to 0.
I looked into questions like here and here, but cannot manage to find a usable answer.
Example:
when John's score was 1: {"name": "John", "score": 1}
when John's score was 0: {"name": "John"}
Upvotes: 0
Views: 148
Reputation: 231
use the answer by @Henrik changing the annotation to JsonInclude.Include.NON_DEFAULT. Hope this is what you are expecting
Upvotes: 2
Reputation: 7157
Decided to try out @BalakrishnaAvulapati's proposal, and it definitely seems like the correct approach.
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Player {
private String nick;
private Integer score;
// Omitting getter/setter for nick field
public Integer getScore() {
return score;
}
public void setScore(int score) {
this.score = score == 0 ? null : Integer.valueOf(score);
}
}
Upvotes: 0