Java中使用Jackson JSON注解实现字段嵌套的简便方法?
实现Jackson字段嵌套无需创建独立对象
我希望无需为仅存储字符串的content值创建新的独立对象,直接通过注解实现字段嵌套,比如这样写:
@JsonNestedProperty("value.content") String value = "my_value";
期望生成的JSON:
{ "value": { "content": "my_value" } }
但目前只能通过创建独立类来实现:
@JsonProperty("value") MyContent value; class MyContent { @JsonProperty("content") String content = "my_value"; }
解决方法
方法1:用@JsonGetter和@JsonSetter手动处理嵌套
不需要额外创建类,直接通过getter/setter方法模拟嵌套结构,Jackson支持直接解析点分隔的路径:
public class MyDto { private String value; @JsonGetter("value.content") public String getValue() { return value; } @JsonSetter("value.content") public void setValue(String value) { this.value = value; } }
这样序列化后就能得到目标嵌套JSON,反序列化时也能正确将value.content路径下的值映射到value字段。
方法2:自定义@JsonNestedProperty注解(进阶复用)
如果需要在多处复用这种嵌套逻辑,可以自定义注解和对应的序列化/反序列化器:
- 定义自定义注解:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface JsonNestedProperty { String value(); // 嵌套路径,如"value.content" }
- 实现自定义序列化器:
public class NestedPropertySerializer extends JsonSerializer<String> { @Override public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException { try { // 获取当前字段及其注解 Field field = gen.getCurrentValue().getClass().getDeclaredField(gen.getOutputContext().getCurrentName()); JsonNestedProperty annotation = field.getAnnotation(JsonNestedProperty.class); if (annotation == null) { gen.writeString(value); return; } String[] pathSegments = annotation.value().split("\\."); // 逐层构建嵌套对象 for (int i = 0; i < pathSegments.length - 1; i++) { gen.writeFieldName(pathSegments[i]); gen.writeStartObject(); } // 写入最终字段值 gen.writeStringField(pathSegments[pathSegments.length - 1], value); // 关闭所有嵌套对象 for (int i = 0; i < pathSegments.length - 1; i++) { gen.writeEndObject(); } } catch (NoSuchFieldException e) { throw new RuntimeException("Failed to find field for nested property", e); } } }
- 搭配注解使用:
@JsonSerialize(using = NestedPropertySerializer.class) @JsonNestedProperty("value.content") String value = "my_value";
如果需要支持反序列化,还需要编写对应的JsonDeserializer实现,逻辑类似,反向解析嵌套路径的值到字段。
内容的提问来源于stack exchange,提问作者planktonchumbucket
相关产品推荐
相关产品推荐

