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

Jackson如何使用字段级注解实现单个序列化字段的外层包裹?

Jackson单字段序列化外层包裹节点实现方案

你可以通过自定义序列化器+少量注解的方式实现需求,一次开发即可复用给所有需要包裹的字段,无需为每个字段单独编写Map或封装类:


实现步骤

1 编写通用字段包裹序列化器

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;

public class FieldWrapperSerializer extends StdSerializer<Object> implements ContextualSerializer {
    // 存储外层包裹节点名
    private String wrapperName;
    // 存储原字段名
    private String originFieldName;

    public FieldWrapperSerializer() {
        super(Object.class);
    }

    public FieldWrapperSerializer(String wrapperName, String originFieldName) {
        super(Object.class);
        this.wrapperName = wrapperName;
        this.originFieldName = originFieldName;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        // 输出外层包裹节点
        gen.writeStartObject();
        // 输出原字段名和对应值
        gen.writeObjectField(originFieldName, value);
        gen.writeEndObject();
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        // 读取字段上的JsonProperty注解,获取配置的外层包裹名
        JsonProperty jsonProperty = property.getAnnotation(JsonProperty.class);
        if (jsonProperty != null && !jsonProperty.value().isBlank()) {
            return new FieldWrapperSerializer(jsonProperty.value(), property.getName());
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}

2 业务类添加注解

直接在需要包裹的字段上添加两个注解即可:

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.annotation.JsonProperty;

class A {
   int field1;

   // value配置外层包裹节点的名称
   @JsonProperty(value = "parent")
   @JsonSerialize(using = FieldWrapperSerializer.class)
   String field2;
}

序列化后即可输出你需要的格式:

{
   "field1": 77,
   "parent": {
       "field2": "Success"
   }
}

其他说明

  • 该方案兼容所有Jackson 2.x版本,支持任意类型的字段包裹
  • 有多个字段需要处理时,仅需给对应字段加上上述两个注解,修改@JsonProperty的value值为对应外层节点名即可
  • 如果需要更简化的单注解实现,可以自定义一个组合注解,把@JsonSerialize和包裹名配置整合到同一个注解中,进一步减少重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 16:36:03