We want to create a json string for some Java objects, but we don't want empty strings or empty arrays to be added to the json output. We are using Eclipse Yasson 1.0.1 to create the json strings.
Actually what we want is the behaviour of JsonInclude.Include.NON_EMPTY of Jackson, but we can not use Jackson.
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private int id;
private String name;
private String email;
private String birthPlace;
private List<String> phones;
}
public class Test {
public static void main(String[] args) {
Jsonb jsonb = JsonbBuilder.create();
Person person = Person.builder()
.id(1)
.name("Gert")
.email("") //Should not be in output -> nok
.birthPlace(null) //Should not be in output -> ok
.phones(new ArrayList<>()) //Should not be in output -> nok
.build();
String toJsonString = jsonb.toJson(person);
System.out.println(toJsonString);
}
}
The current output is
{"email":"","id":1,"name":"Gert","phones":[]}
But we want it to be
{"id":1,"name":"Gert"}
I have checked the documentation and the code, and
Yassononly provide an option for ignoring null values (which is activated by default).The only option seems to be to implement a custom
JsonbSerializerfor yourPersonclass and not serialize the field when the value is empty.And initialize
Yassonwith the following code: