如何防止使用 Eclipse Yasson 输出空字符串和空集合

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

我们想为一些 Java 对象创建一个 json 字符串,但我们不希望将空字符串或空数组添加到 json 输出。我们正在使用 Eclipse Yasson 1.0.1 创建 json 字符串。

其实我们想要的是JacksonJsonInclude.Include.NON_EMPTY的行为,但是我们不能使用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);
    }
}

当前输出为

{"email":"","id":1,"name":"Gert","phones":[]}

但我们希望它是

{"id":1,"name":"Gert"}

我查看了文档和代码,Yasson只提供了忽略空值的选项(默认激活)

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

唯一的选择似乎是为您的 Person class 实现自定义 JsonbSerializer,并且在值为空时不序列化该字段。

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

并使用以下代码初始化 Yasson

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