我遇到了在另一个JAXB对象中映射JAXB对象集合的麻烦,有人看到我的结构问题在下面吗?我使用以下代码获得一个空的formerUsers ArrayList:
String test="<SSO-Request><User-Id>3119043033121014002</User-Id><Former-User-Ids><User-Id>3119043033121014999</User-Id><User-Id>3119043033121014555</User-Id></Former-User-Ids></SSO-Request>";
SSORequest ssoRequest=null;
try{
JAXBContext jaxbContext = JAXBContext.newInstance(SSORequest.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
ssoRequest = (SSORequest) unmarshaller.unmarshal(new StringReader(test));
}
catch(Exception e){
e.printStackTrace();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="SSO-Request")
public class SSORequest {
@XmlElement(name="User-Id")
String userId;
@XmlElementWrapper(name="Former-User-Ids")
List<FormerUser> formerUsers;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Former-User-Ids")
public class FormerUser {
@XmlElement(name="User-Id")
String userId;
}
答案 0 :(得分:2)
您的映射过于复杂,这就是您所需要的:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="SSO-Request")
public class SSORequest {
@XmlElement(name="User-Id")
String userId;
@XmlElementWrapper(name="Former-User-Ids")
@XmlElement(name="User-Id")
List<String> formerUserIds;
}
答案 1 :(得分:1)
您应该像skaffman建议的那样更改映射,或者您应该更改xml:
<SSO-Request><User-Id>3119043033121014002</User-Id><Former-User-Ids><Former-User><User-Id>3119043033121014999</User-Id></Former-User><Former-User><User-Id>3119043033121014555</User-Id></Former-User></Former-User-Ids></SSO-Request>
并更改FormerUser xml元素的名称:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Former-User")
public class FormerUser {
@XmlElement(name="User-Id")
String userId;
}
答案 2 :(得分:0)
如果属性应为List&lt; FormerUser&gt;那么你需要一种方法来告诉JAXB ID对应的内容。如果FormerUsers的数据将出现在文档中,那么您可以使用@XmlID和@XmlIDREF进行此映射:
如果FormerUsers的数据发生在文档之外,那么您可以使用我在下面的答案中描述的策略: