You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Jackson ObjectMapper生成不含空值与未定义属性的POJO

问题描述

当前使用Jackson的ObjectMapper做JSON转POJO时,得到的结果包含值为null的属性(如propertyB)和JSON中未出现的非必填属性(如propertyC)。需要实现反序列化后仅保留propertyA=1,过滤两类属性:

  • JSON中未出现的非必填属性
  • 值为null的属性

现有ObjectMapper转换方法

public <T> T convertJSONtoPOJO(String inputJSON,
                               Class<T> valueType) throws Exception {
    try {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        return objectMapper.readValue(inputJSON, valueType);
    } catch (Exception exception) { 
        //my exception which doesnt matter now
    }
}

输入JSON

{
    "propertyA": "1",
    "propertyB": null 
}

对应的POJO

@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
public class MyClazz {
    String propertyA;
    String propertyB;
    String propertyC;
}
解决方案

由于Java对象实例化后类定义的属性必然存在,只能通过序列化过滤或反序列化前预处理JSON来实现“仅保留目标属性”的效果,以下是两种可行方案:

方案一:注解+序列化配置过滤null值

  1. 给POJO添加序列化过滤注解,让Jackson序列化时自动忽略null值属性:
@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClazz {
    String propertyA;
    String propertyB;
    String propertyC;
}
  1. 在转换方法中全局配置序列化规则,确保所有转换后的POJO序列化时都过滤null值:
public <T> T convertJSONtoPOJO(String inputJSON,
                               Class<T> valueType) throws Exception {
    try {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        // 序列化时忽略所有null值属性(包含JSON未出现的默认null属性)
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper.readValue(inputJSON, valueType);
    } catch (Exception exception) { 
        //my exception which doesnt matter now
    }
}

这种方案下,Java对象本身仍包含所有属性,但序列化输出时只会保留propertyA=1。

方案二:预处理JSON过滤null节点后再反序列化

先将JSON解析为JsonNode,过滤掉值为null的节点,再将处理后的JSON反序列化为POJO:

public <T> T convertJSONtoPOJO(String inputJSON,
                               Class<T> valueType) throws Exception {
    try {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        // 解析原始JSON为JsonNode
        JsonNode rootNode = objectMapper.readTree(inputJSON);
        ObjectNode filteredNode = objectMapper.createObjectNode();
        // 遍历节点,仅保留非null的字段
        rootNode.fields().forEachRemaining(entry -> {
            if (!entry.getValue().isNull()) {
                filteredNode.set(entry.getKey(), entry.getValue());
            }
        });
        // 反序列化过滤后的JSON
        return objectMapper.treeToValue(filteredNode, valueType);
    } catch (Exception exception) { 
        //my exception which doesnt matter now
    }
}

此方案会先剔除JSON中的null字段,再反序列化,最终POJO中propertyB和propertyC仍为null,但后续序列化时配合NON_NULL规则即可只输出propertyA。

内容的提问来源于stack exchange,提问作者ICT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:30:56