如何在使用 Jackson Serializer 进行序列化期间从 JSON 中排除空列表?

问题描述 投票:0回答:1

如何避免使用 Jackson Custom 序列化器写入空列表?目前,它正在添加空列表:

"list" : [ ]
,但我希望它完全跳过它,无论是使用一些注释还是使用自定义密封器。我已经使用
Collections.emptyList()
创建了演示,我知道如果我删除,它将跳过空列表,但这仅用于演示目的,我想使用其他方法跳过:

我的班级:

@Data
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@AllArgsConstructor
public class MyClass {
    private String type;

    private String name;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @JsonSerialize(using = CustomSearilizer.class)
    private List<Object> list;
}

自定义序列化器:

public class CustomSearilizer extends JsonSerializer<List<Object>> {
    @Override
    public void serialize(final List<Object> context, final JsonGenerator jsonGenerator, final SerializerProvider serializers) throws IOException {

        jsonGenerator.writeStartArray();

        context.stream().forEach(item -> {
            if (item instanceof Map) {
                Map<String, String> entries = (Map<String, String>) item;
                entries.entrySet().stream().forEach(entry -> {
                    try {
                        jsonGenerator.writeStartObject();
                        jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
                        jsonGenerator.writeEndObject();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }

                });
            }
        });

        jsonGenerator.writeEndArray();
    }
}

主要:

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

        final MyClass myClass = new MyClass("My Name", "My Type", Collections.emptyList());

        System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(myClass));
    }
}

这为我提供了以下 JSON:

{
  "type" : "My Name",
  "name" : "My Type",
  "list" : [ ]
}

我想按照 JSON 创建它:

{
  "type" : "My Name",
  "name" : "My Type"
}

这只是一个演示,所以我添加了 collections.emptyList 来重新创建问题,但是有什么方法可以在使用 Customsealizer 时跳过在 JSON 中添加这些emptyList 吗?

java json jackson jackson-databind jackson2
1个回答
0
投票

我刚刚运行了一个测试,只需将注释

@JsonInclude(JsonInclude.Include.NON_EMPTY)
添加到序列化类就可以了。不需要采取其他行动。没有自定义序列化程序,也没有对 ObjectMapper 配置进行修改。这是解释该示例的文章: Jackson JSON - @JsonIninclude NON_EMPTY 示例

© www.soinside.com 2019 - 2024. All rights reserved.