0
votes

I have issue working with JAXB, and list of objects. JAXB is used to marshall/unmarshall XMLs from REST api developed in Spring 4. The class structure doesn't much xml structure, in place where I use ArrayList

I have Java Business Object Model as follows:
Client:

@XmlRootElement(name="client")
public class Client {
@XmlElement
public Integer age = Integer.valueOf(0);

 public Client() {
    super();
 }
}

Offer (root element):

@XmlRootElement
@XmlSeeAlso(Client.class)
public class Offer {
@XmlElement
public ArrayList<Client> clients = new ArrayList<Client>();
public Boolean decission = Boolean.FALSE;

 public Offer() {
    super();
 }
}  

and unmarshaller:

public static Offern unmarshalXMLOffer(String httpMessage) throws Exception{
    logger.debug("unmarshal: receved data to unmarshal:  " + httpMessage);
    JAXBContext jaxbContext = JAXBContext.newInstance(Offer.class, Client.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    StringReader reader = new StringReader(httpMessage);
    Offer ca = (Offer)jaxbUnmarshaller.unmarshal(reader);
    return ca;
}

The issue:
When I send:

<Offer>
  <clients>
    <client>
        <age>21</age>
    </client>
  </clients>
  <decission>false</decission>
</Offer>

I got: Offer.Client.age = 0
but if i send to unmarshaller this:

<Offer>
  <clients>
        <age>21</age>
  </clients>
  <decission>false</decission>
</Offer>

I got: Offer.Client.age = 21 - right value.

According to my best knowledge and some JAXB experience i did few things:

  • i tried to use annotation XMLSeeAlso
  • made custom wrapper class for client list

    @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlSeeAlso(Client.class) public class ClientsXMLWrapper { @XmlElement(name = "clients") private List clients;

    public ClientsXMLWrapper(){
    
    }
    
    public ClientsXMLWrapper(List<Client> clientsList){
        clients = clientsList;
    }
    
    public List<Client> getClients() {
        return clients;
    }
    public void setClients(List<Client> clients) {
        this.clients = clients;
    }   
    

    }

  • i did different JAXB initializations:

    1. JAXBContext jaxbContext = JAXBContext.newInstance(Offer.class, Client.class, ClientsXMLWrapper.class);
    2. JAXBContext jaxbContext = JAXBContext.newInstance(Offer.class, Client.class);
    3. JAXBContext jaxbContext = JAXBContext.newInstance(Offer.class, ClientsXMLWrapper.class);

Nothing helped so far. Could you please help me resolve that issue? KOch.

1

1 Answers

1
votes

Try:

@XmlElementWrapper(name="clients")
@XmlElement(name="client")
public ArrayList<Client> clients = new ArrayList<Client>();