我们想为一些 Java 对象创建一个 json 字符串,但我们不希望将空字符串或空数组添加到 json 输出中。我们正在使用 Eclipse Yasson 1.0.1 创建 json 字符串。
实际上我们想要的是JsonInclude.Include.NON_EMPTY
杰克逊的行为,但我们不能使用杰克逊。
@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"}