我对 XML DTO 有疑问。我试图在 Spring Boot 3.3.5 和 jackson-dataformat-xml v2.18.2 中组装它。这里的问题是我有两个列表,其中包含 DTO 中同名的子项。
DTO 看起来像这样:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Builder
public class PlayerActivityDto {
@JacksonXmlProperty(localName = "playerActivityId", isAttribute = true)
private String brandId;
@JacksonXmlProperty(localName = "player")
private PlayerDto player;
@JacksonXmlProperty(localName = "playerActivityDetail")
private PlayerActivityDetailDto playerActivityDetail;
@Setter
@Getter
@JacksonXmlProperty(localName = "summaryBalance")
@JacksonXmlElementWrapper(localName = "startingBalanceList")
private List<SummaryBalanceDto> startingBalanceList;
@Getter
@Setter
@JacksonXmlProperty(localName = "summaryBalance")
@JacksonXmlElementWrapper(localName = "endingBalanceList")
private List<SummaryBalanceDto> endingBalanceList;
@JacksonXmlProperty(localName = "playerMovement")
@JacksonXmlElementWrapper(localName = "playerMovementList")
private List<FundsMovementDto> playerMovementList;
}
我遇到的问题是名为endingBalanceList 和startingBalanceList 的两个列表。 AFAIK,
@JacksonXmlProperty(localName = "summaryBalance")
应将列表endingBalanceList 和startingBalanceList 的子项命名为“summaryBalance”,并应生成有效的XML。
然而,杰克逊产生了这个例外:
无法评估类型 [class PlayerActivityDto] 的 Jackson 序列化:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:属性“summaryBalance”的 getter 定义冲突:PlayerActivityDto#getStartingBalanceList() 与 PlayerActivityDto#getEndingBalanceList()
我尝试为这些列表提供自己的 setter 和 getter,但这似乎没有帮助。
所以我实际上在一些 Github 问题论坛上找到了解决方法。
为了解决这个问题,我必须创建一个新类来包装列表。
@Builder
public class PlayerActivityDto {
@JacksonXmlProperty(localName = "playerActivityId", isAttribute = true)
private String brandId;
@JacksonXmlProperty(localName = "player")
private PlayerDto player;
@JacksonXmlProperty(localName = "playerActivityDetail")
private PlayerActivityDetailDto playerActivityDetail;
@JacksonXmlProperty(localName = "startingBalanceList")
private SummaryBalanceListWrapper startingBalanceList;
@JacksonXmlProperty(localName = "endingBalanceList")
private SummaryBalanceListWrapper endingBalanceList;
@JacksonXmlProperty(localName = "playerMovement")
@JacksonXmlElementWrapper(localName = "playerMovementList")
private List<FundsMovementDto> playerMovementList;
}
@Builder
public class SummaryBalanceListWrapper {
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "summaryBalance")
private List<SummaryBalanceDto> summaryBalanceList;
}
Jackson 开发人员似乎不会很快解决这个问题,所以我希望这对遇到同样问题的其他开发人员有所帮助。