如何避免使用Jackson自定义序列化程序编写空列表?目前,它正在添加空列表:"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吗?
1条答案
按热度按时间sc4hvdpw1#
我只是运行了一个测试,只是将注解
@JsonInclude(JsonInclude.Include.NON_EMPTY)
添加到序列化的类中就完成了任务。无需采取其他行动。没有自定义序列化程序,也没有对ObjectMapper配置的修改。下面是文章的eaplains的例子:Jackson JSON - @JsonInclude NON_EMPTY Example