【问题标题】:How can I prevent empty strings and empty collections to be outputted with eclipse Yasson如何防止使用 eclipse Yasson 输出空字符串和空集合
【发布时间】:2020-01-02 17:22:19
【问题描述】:

我们想为一些 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"}

【问题讨论】:

    标签: java json jsonb-api yasson


    【解决方案1】:

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

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

    唯一的选择似乎是为您的Person 类实现自定义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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多