【发布时间】:2021-07-08 05:20:37
【问题描述】:
我在应用服务器项目(不是 Spring Boot)中使用 RestTemplate 从端点获取实体。
实体 DTO(使用 JAXB 注释)是:
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "entity")
public class EntityDTO {
private Integer id; // this was missing
private List<String> parameterName; // parameter names
public EntityDTO() {
}
@XmlElementWrapper(name = "parameterNames")
@XmlElement(name = "parameterName")
public List<String> getParameterName() {
return parameterName;
}
public void setParameterName(List<String> parameterName) {
this.parameterName = parameterName;
}
@XmlElement(name = "id")
public Integer getId() {
return id;
}
// this was returning Integer instead of void
public void setId(Integer id) {
this.id = id;
}
}
因此,在端点中,例如以这种方式返回实体:
{
"entity": {
"id": 1,
"parameterNames": {
"parameterName": [
"param1",
"param2"
]
}
}
}
我正在使用带有以下代码的 RestTemplate 对上一个端点执行 GET:
...
HttpEntity<EntityDTOO> response = restTemplate.exchange(
uri,
HttpMethod.GET,
httpEntity,
EntityDTO.class);
...
但是 RestTemplate 以这种方式解组实体:
id: 1
parameterName: null
但我期待:
id: 1
parameterName: ["param1", "param2"]
有人知道如何使用 RestTemplate 识别 @XmlElementWrapper(name = "parameterNames") 注释吗?
提前致谢。
【问题讨论】:
-
我认为注释没有任何问题。您确定要创建包含元素的列表吗?您可能没有正确地构造对象。
-
我确实在您的代码中发现了一些错误。我将编辑您的代码以更正它们。
-
除非您提供更多代码,否则我无法继续。例如,您用来测试的 URI 是什么?你是如何创建
HttpEntity的?这些是非常重要的部分,很可能是错误所在。正如我之前提到的,JAXB 部分工作正常。您可能需要创建一个HttpMessageConverter才能使其正常工作,除非您提供所有这些信息,否则我无法确定。
标签: jaxb resttemplate spring-resttemplate