jackson - 如何将 XML 字符串反序列化为使用包含 @XmlElement 的 JAXB 注释的复合 Java 对象
问题描述
我有以下 JAXB 注释类:
@Data
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="Channels", namespace="http://abc.channeltypes")
public class Channels {
@XmlElement(name = "Channel", required = true)
private @Valid @NotNull List<Channel> channels;
}
@Data
@Getter
@XmlRootElement(name = "Channel")
@XmlAccessorType(XmlAccessType.NONE)
public class Channel {
@XmlElement(name = "ChannelId")
private Integer channelId;
@XmlElement(name = "Name", required = true)
private @NotEmpty String name;
@XmlElement(name = "Type", required = true)
private @NotEmpty String type;
当我尝试反序列化输入时,出现以下错误:
无法识别的字段“Channel”(a.request.Channels 类),在 [Source: (StringReader); 处未标记为可忽略(一个已知属性:“channels”]);行:1,列:136](通过引用链:a.request.Channels["Channel"])
我正在尝试为发布请求创建一个模拟服务器,因此当我以 JAXB xml 格式获取请求时,我尝试使用映射器来读取请求正文并将其映射到对象。
mockServer.when(
request()
.withPath("/[a-z]/[a-z]+")
.withMethod("POST")
.withHeader(
new Header("Content-Type", "application/xml"))
)
.respond(
httpRequest -> {
ChannelRef channelRef = new ChannelRef();
String body = httpRequest.getBodyAsString();
Channels channelsRequestBody =new XmlMapper().readValue(body,Channels.class);
channelsRequestBody.getChannels().forEach(channel -> {
Channel createdChannel = createChannel(channel);
channelRef.setChannelId(createdChannel.getChannelId());
channelRef.setExternalId(createdChannel.getExternalId());
});
Response response = getOkResponse(channelRef);
return response()
.withBody(
new ObjectMapper()
.writeValueAsString(
response
)
).withStatusCode(201)
.withContentType(MediaType.APPLICATION_JSON);
}
);
private static Response getOkResponse(ChannelRef channelRef) {
Response response = new Response();
response.setResultCode(HttpStatus.OK.name());
response.setSystemTime(System.currentTimeMillis());
response.setResultObj(channelRef);
return response;
}
有人可以解释我如何解决它。我尝试了很多替代方案,但似乎没有奏效。
解决方案
我找到了解决方案。
要传递 XML 内容,您需要将内容包装在 Reader 中,然后将其解组:
JAXBContext jaxbContext = JAXBContext.newInstance(Channels.class); 解组器 unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(body); 频道 a= (频道) unmarshaller.unmarshal(reader);
推荐阅读
- java - LocalDateTime.format(DateTimeFormatter) 和 DateTimeFormatter.format(TemporalAccessor) 有什么区别?
- sapui5 - smarttable 请求不必要的后端调用
- c++ - 图像过滤器内核边缘问题(反映边缘值)
- c# - 如何让我的数据库值(使用 MySQL)加载到场景中并可以看到?
- docker - Docker compose 服务无法从 localhost 访问
- python - 如何创建一个充满流程输出的字典?
- bootstrap-4 - 为什么 Bootstrap 4 默认使用 A3 页面大小?
- r - 使用 stat="count" 时将 geom_bar 从高到低重新排序
- php - 有没有办法选择最后一条记录然后用关系过滤?
- sql - 用于添加时间到日期的 ssis 表达式