我有从REST返回的xml,它看起来如下:
<customers>
<customer>
<addressline1>111 E. Las Olas Blvd</addressline1>
<addressline2>Suite 51</addressline2>
<city>Fort Lauderdale</city>
<creditLimit>100000</creditLimit>
<customerId>1</customerId>
<discountCode>
<discountCode>56</discountCode>
<rate>0.00</rate>
</discountCode>
<email>jumbocom@gmail.com</email>
<fax>305-777-4635</fax>
<name>Kupa</name>
<phone>305-777-4632</phone>
<state>FL</state>
<zip>
<areaLength>22.0</areaLength>
<areaWidth>23.0</areaWidth>
<radius>50.0</radius>
<zipCode>90-200</zipCode>
</zip>
</customer>
</customers>
我正在尝试解组列表,但列表始终为空。也许原因是在Customer类中,Zip和DiscountCode是其他实体,所以我只有XML作为字符串,它不能从中创建实体。
这些是我的java类:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customers
{
@XmlElement
private List<Customer> customers = new ArrayList<Customer>();
public List<Customer> getCustomers()
{
return customers;
}
}
@Entity
@Table(name = "customer")
@XmlRootElement(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "customer_id")
private Integer customerId;
@Column(name = "name")
private String name;
@Column(name = "addressline1")
private String addressline1;
@Column(name = "addressline2")
private String addressline2;
@Column(name = "city")
private String city;
@Column(name = "state")
private String state;
@Column(name = "phone")
private String phone;
@Column(name = "fax")
private String fax;
@Column(name = "email")
private String email;
@Column(name = "credit_limit")
private Integer creditLimit;
@JoinColumn(name = "discount_code", referencedColumnName = "discount_code")
@ManyToOne(optional = false)
private DiscountCode discountCode;
@JoinColumn(name = "zip", referencedColumnName = "zip_code")
@ManyToOne(optional = false)
private MicroMarket zip;
// later only setters and getters
}
这就是我解组的方式:
JAXBContext context = JAXBContext.newInstance(Customers.class, Customer.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Customers customers = (Customers) unmarshaller.unmarshal(new StringReader(allXmlString));
我见过类似的话题,但其中任何一个都对我有所帮助。为什么解组后我的列表总是空的?
感谢您的帮助。
答案 0 :(得分:2)
customers
字段的默认映射将查找名为customers
的XML元素。在@XmlElement
注释上,您需要指定要映射到名为customer
的XML元素。
@XmlElement(name="customer")
private List<Customer> customers = new ArrayList<Customer>();
<强>客户强>
以下是完整的Customers
类的外观:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customers
{
@XmlElement(name="customer")
private List<Customer> customers = new ArrayList<Customer>();
public List<Customer> getCustomers()
{
return customers;
}
}
了解更多信息