Jackson JAXB序列化忽略JsonProperty,XML与JSON格式不一致问题
问题:Jackson序列化JSON时忽略@JsonProperty,优先使用JAXB注解
我需要让某个字段在XML和JSON序列化时呈现不同格式,但Jackson序列化JSON时只读取JAXB的@XmlElement注解,完全忽略了Jackson的@JsonProperty注解。
代码示例
实体类字段
@XmlElementWrapper(name = "ParticipantBindings") @XmlElement(name = "ParticipantBinding") @com.fasterxml.jackson.annotation.JsonProperty("participantBindings") // 该注解被忽略? public List<ParticipantBinding> getParticipantBindings() { return participantBindings; }
Spring Boot控制器
@GetMapping(path = "/{id}", produces = {MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Participant> getParticipantById(@PathVariable("id") int id) { Participant p = participantDao.getParticipantFull(id); if (p == null) { throw new ResourceNotFoundException(); } else { return ResponseEntity.ok(p); } }
预期与实际结果
预期效果
- 请求头
Accept为application/xml时:
<ParticipantBindings> <ParticipantBinding>...</ParticipantBinding> <ParticipantBinding>...</ParticipantBinding> </ParticipantBindings>
- 请求头
Accept为application/json时:
"participantBindings": [ ...]
实际问题
XML格式符合预期,但JSON输出为"ParticipantBinding" : [ ...],@JsonProperty未生效。
解决方法
问题根源是Jackson默认会优先识别JAXB注解,覆盖自身的@JsonProperty。以下两种方案可解决:
方案一:禁用Jackson的JAXB注解支持
通过配置ObjectMapper,关闭JAXB注解的自动检测,让Jackson只处理自身注解。创建Spring配置类:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); // 移除JAXB注解模块,禁用Jackson对JAXB注解的使用 objectMapper.registerModule(new JaxbAnnotationModule()); objectMapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.USE_JAXB_ANNOTATIONS); objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.USE_JAXB_ANNOTATIONS); return objectMapper; } }
方案二:改用Jackson专属XML注解
保留@JsonProperty定义JSON字段名,同时用Jackson自己的XML注解替代JAXB注解,实现两种格式的独立配置:
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; @JacksonXmlElementWrapper(localName = "ParticipantBindings") @JacksonXmlProperty(localName = "ParticipantBinding") @JsonProperty("participantBindings") public List<ParticipantBinding> getParticipantBindings() { return participantBindings; }
这种方式下,XML序列化使用Jackson的XML注解,JSON序列化使用@JsonProperty,互不冲突。
方案选择建议
- 若项目无需兼容其他JAXB序列化场景,方案一更简洁;
- 若必须保留JAXB注解(比如对接其他依赖JAXB的系统),优先选方案二。
内容的提问来源于stack exchange,提问作者Asger Weirsøe
相关产品推荐
相关产品推荐

