2

I'm having troubles mapping a Collection of JAXB object within another JAXB object, anyone see the issue with my structure below? I get an empty formerUsers ArrayList using the following code:

 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;
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
c12
  • 9,557
  • 48
  • 157
  • 253

3 Answers3

2

You're over-complicating your mapping, this is all you need:

@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;
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
1

You should either change your mapping as skaffman proposed, or you should change the 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>

and change the name of the the FormerUser xml element:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Former-User")
public class FormerUser {
    @XmlElement(name="User-Id")
    String userId;
 }
Fortega
  • 19,463
  • 14
  • 75
  • 113
0

If the property should be List<FormerUser> then you will need a way to tell JAXB what the ID corresponds to. If the data for FormerUsers will occur in the document then you can use @XmlID and @XmlIDREF for this mapping:

If the data for FormerUsers will occur outside the document, then you can use the strategy I described in the answer below:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400