我试图XML内容转换为使用JAXB 一个Java对象,而无需使用任何注释。我的XML文件(CustomerDtl.xml)结构如下无法解组使用JAXB Java的一个xml,而无需使用任何annotation-没有错误,但解组是不正确
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<basePojo>
<customerId>C001</customerId>
<customerList>
<Customer>
<name>Ram</name>
<phoneNo>123445</phoneNo>
</Customer>
<Customer>
<name>Tom</name>
<phoneNo>2332322</phoneNo>
</Customer>
</customerList>
</basePojo>
提到的和我的POJO是
BasePojo.java
package pojo;
import java.util.List;
import pojo.Customer;
public class BasePojo {
List<Customer> customerList;
String customerId;
public List<Customer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
}
Customer.java
package pojo;
public class Customer {
private String name;
private String phoneNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
下文提到的一段代码,我已经写XML内容转换成Java对象
try {
JAXBContext jc = JAXBContext.newInstance(BasePojo.class);
StreamSource xml = new StreamSource("CustomerDtl.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<BasePojo> jaxbElementObject = unmarshaller.unmarshal(
xml, BasePojo.class);
BasePojo bPojo = jaxbElementObject.getValue();
System.out.println("id="+bPojo.getCustomerId());
System.out.println("list size="+bPojo.getCustomerList().size());
Iterator iterator = bPojo.getCustomerList().iterator();
while (iterator.hasNext()) {
Customer studentDetails = (Customer) iterator.next();
System.out.println("Print Name:" + studentDetails.getName());
}
} catch (JAXBException e) {
System.out.println("Exception:" + e);
}
和OUT把这个代码是
id=C001
list size=1
list size=[[email protected]]
Print Customer Name:null
后执行这个程序是打印正确的customerId,但它打印错误的客户名单大小。尽管列表大小为1,并且列表包含Customer对象,但是当我遍历列表并尝试获取Customer的不同属性值时,我变为null。
任何人都可以解释我需要纠正什么吗?使用注释我试过了,它按预期工作。没有注释是不可能的?
您可以尝试使用(最终客户的客户:pBojo.getCustomerList()){...而不是你的while循环。我不知道你的泛型迭代器是否导致了这个问题。如果你打算使用迭代器,它应该至少是迭代器 iterator = ...(像Eclipse这样的IDE会给你在当前代码中的警告) –
让我们跳过迭代部分。为什么列表大小是1,有什么想法? – Bikku
好问题。你使用的是什么注释使它工作? –