使用ArrayList

时间:2016-12-06 10:52:15

标签: xml java-ee jaxb

我有使用JAXB和对象列表的问题。 JAXB用于对Spring 4中开发的REST api中的XML进行编组/解组。 类结构没有多少xml结构,就在我使用ArrayList

的地方

我有Java业务对象模型如下:
客户端:

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

 public Client() {
    super();
 }
}

优惠(根元素):

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

 public Offer() {
    super();
 }
}  

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

问题:
当我发送:

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

我得到了: Offer.Client.age = 0
但如果我发送给unmarshaller:

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

我得到了: Offer.Client.age = 21 - 正确的价值。

根据我的最佳知识和一些JAXB经验,我做了一些事情:

  • 我尝试使用注释XMLSeeAlso
  • 为客户列表

    制作自定义包装类

    @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlSeeAlso(Client.class) 公共类ClientsXMLWrapper {     @XmlElement(name =&#34; clients&#34;)     私人列表客户;

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

    }

  • 我做了不同的JAXB初始化:

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

到目前为止没有任何帮助。你能帮我解决一下这个问题吗? KOCH。

1 个答案:

答案 0 :(得分:1)

尝试:

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