javajsonjsonb-apiyasson

How can I prevent empty strings and empty collections to be outputted with eclipse Yasson


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"}

Solution

  • I have checked the documentation and the code, and Yasson only provide an option for ignoring null values (which is activated by default).

    JsonbConfig config = new JsonbConfig().withNullValues(false);
    Jsonb jsonb = JsonbBuilder.create(config);
    

    The only option seems to be to implement a custom JsonbSerializer for your Person class and not serialize the field when the value is empty.

    public class PersonSerializer implements JsonbSerializer<Person> {
        @Override
        public void serialize(Person person, JsonGenerator generator, SerializationContext serializationContext) {
            generator.writeStartObject();
            generator.write("id", person.getId());
            if (person.getName() != null && !person.getName().isEmpty()) {
                generator.write("name", person.getName());
            }
            if (person.getEmail() != null && !person.getEmail().isEmpty()) {
                generator.write("email", person.getEmail());
            }
            // ...
            generator.writeEnd();
        }
    }
    

    And initialize Yasson with the following code:

    JsonbConfig config = new JsonbConfig().withSerializers(new PersonSerializer());
    Jsonb jsonb = JsonbBuilder.create(config);