Jackson 2.0序列化POJO时嵌套Employer对象缺失问题求助
解决Jackson序列化时嵌套内部类字段消失的问题
看起来你遇到的核心问题是Jackson序列化Bus对象时,嵌套的Employer字段完全消失,甚至尝试某些注解时出现栈溢出。结合你的代码和描述,我来帮你分析原因并给出解决方案:
核心原因:非静态内部类的序列化陷阱
你的Student和Employer都是Bus的非静态内部类,这类内部类会隐式持有外部类Bus的引用。Jackson在序列化时:
- 会尝试序列化这个隐式引用,导致循环引用,进而引发栈溢出(这就是你遇到栈溢出的原因)
- 如果内部类实例没有正确关联到外部类,Jackson会直接忽略该字段,导致Employer不出现在JSON中
解决方案步骤
1. 将内部类改为静态内部类
这是最关键的一步,静态内部类不持有外部类的引用,Jackson可以正常序列化它们。修改代码如下:
@JsonIgnoreProperties({"duration", "errorCode", "haveFieldsChanged", "serviceRequestToken", "storedProcDuration"}) class Bus extends AbstractBaseClass implements Serializable{ @JsonIgnore private static final long serialVersionId = 1; @JsonProperty("name") String name; @JsonProperty("id") int id; @JsonProperty("students") List<Student> students; @JsonProperty("employer") Employer employer; // 改为静态内部类 @JsonRootName(value = "student") static class Student implements Serializable{ // student字段 } // 改为静态内部类 @JsonRootName(value = "statusType") static class Employer implements Serializable{ @JsonProperty("id") int id; } // Getter和Setter方法 }
2. 确保Employer字段不为null(或配置序列化null字段)
如果你的Bus对象中employer字段是null,Jackson默认会忽略null字段。如果需要序列化null值,可以在ObjectMapper中添加配置:
private String serializeBus(Bus bus) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // 添加这行,序列化所有字段包括null mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); String json = null; try { json = mapper.writeValueAsString(bus); } catch (JsonProcessingException e) { logger.error("Error serializing bus"); throw new Exception(e); } return json; }
3. 移除不必要的注解(可选)
你给内部类添加了@JsonRootName,但这个注解只有在开启WRAP_ROOT_VALUE特性时才会生效(即把每个对象包裹在指定名称的根节点里)。如果你不需要这个功能,可以直接移除该注解,避免混淆。
验证效果
修改后重新序列化Bus对象,Jackson应该会正常输出包含employer字段的JSON:
{ "name":"Sean", "id": 1, "students":[...], "employer": {"id": 123} }
内容的提问来源于stack exchange,提问作者sruffatti
相关产品推荐
相关产品推荐

