我有一个这样的DTO:
package ...;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.time.LocalDateTime;
import java.util.List;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JacksonXmlRootElement(localName = "root")
public class RootDto {
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
LocalDateTime time;
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JacksonXmlElementWrapper(localName = "times")
@JacksonXmlProperty(localName = "time")
List<InternalTimeDto> times;
...
}
package ...;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.time.LocalDateTime;
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class InternalTimeDto {
@JacksonXmlProperty(isAttribute = true)
Long id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
LocalDateTime time;
}
据我所知,问题是time
字段和times
字段的元素具有相同的名称。有没有一种方法可以解决冲突,而不将一个time
重命名为其他东西?理论上,不应该有任何冲突,因为time
字段和列表项处于不同的级别。
XML示例:
<root>
<time>2020-11-18 12:34</time>
<times>
<time id="5">2020-11-18 10:00</time>
<time id="6">2020-11-17 15:30</time>
</times>
...
</root>
我找到了几个答案,但是当两个具有相同名称的不同对象位于同一层时,它们解决了问题。
JSON也被使用:
{
"time": "2020-11-18 12:34",
"times": [
{
"id": 5,
"time": "2020-11-18 10:00"
},
{
"id": 6,
"time": "2020-11-17 15:30"
}
],
...
}
解决由于多重定义属性time
保存xml格式而导致的擦除冲突的一种方法是创建一个Times
类,将List<InternalTimeDto>
包装:
public class Times {
@JacksonXmlProperty(localName = "time")
@JacksonXmlElementWrapper(useWrapping = false)
List<InternalTimeDto> times;
}
所以你的RootDto
类可以这样重写:
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@FieldDefaults(level = AccessLevel.PRIVATE)
@JacksonXmlRootElement(localName = "root")
public class RootDto {
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
LocalDateTime time;
@JsonInclude(value = JsonInclude.Include.NON_NULL)
private Times times; //<-- times field instead of List<InternalTimeDto> times
}
您的InternalTimeDto
类需要JacksonXmlText
注释time
字段:
@Getter
@Setter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class InternalTimeDto {
@JacksonXmlProperty(isAttribute = true)
Long id;
@JacksonXmlText
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
LocalDateTime time;
}