2011-03-28 253 views
2

我遇到了在另一個JAXB對象內映射JAXB對象集合的麻煩,任何人都會在下面看到我的結構有問題?我得到一個空的ArrayList formerUsers使用下面的代碼:JAXB嵌套集合

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; 
} 

回答

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

你應該要麼改變你的映射,提出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> 

和更改的XML FormerUser元素的名稱:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name="Former-User") 
public class FormerUser { 
    @XmlElement(name="User-Id") 
    String userId; 
}