java - 使用 JAXB 解组 XML 返回 NullPointerException
问题描述
我制作了一个 RESTful api,它返回以下简单的 XML:
<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<GoldPriceArray>
<GoldPrice>
<Date>2020-06-15</Date>
<Price>219.01</Price>
</GoldPrice>
<GoldPrice>
<Date>2020-06-16</Date>
<Price>216.73</Price>
</GoldPrice>
</GoldPriceArray>
我正在尝试取消日期和价格,但无法进入嵌套元素 - 我的代码在 unmarchaller() 方法上返回 NullPointerException。这是我的代码
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "GoldPriceArray")
public class GoldRates {
private List<GoldRate> goldRateList;
private String goldValue;
public GoldRates() {}
public GoldRates(String goldPrice, List<GoldRate> goldRateList) {
this.goldRateList = goldRateList;
this.goldValue = goldPrice;
}
@XmlElement
public List<GoldRate> getList() {
return goldRateList;
}
public void setList(ArrayList<GoldRate> goldRateList) {
this.goldRateList = goldRateList;
}
@XmlElement
public String getPrice() {
return goldValue;
}
public void setPrice(String goldPrice) {
this.goldValue = goldPrice;}
public class GoldRate {
@XmlElement(name = "Date")
private String dateOfPrice;
@XmlElement(name = "Price")
private String price;
public GoldRate() {
}
public GoldRate(String date, String value) {
this.dateOfPrice = date;
this.price = value;
}
public String getDate() {
return dateOfPrice;
}
public void setDate(String date) {
this.dateOfPrice = date;
}
public String getValue() {
return price;
}
public void setValue(String value) {
this.price = value;
}
@Override
public String toString() {
return "Date: " + dateOfPrice + " value: " + price;
}
}
在 System.out.println() 上返回 NullPointerException 的 Unmaralling 方法
public void unmarshaller(String xml) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(GoldRates.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
GoldRates goldRates = (GoldRates) jaxbUnmarshaller.unmarshal(new StringReader(xml));
System.out.println(goldRates.getList().get(0).getValue() + " " + goldRates.getList().get(0).getDate());
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
关于这个有什么提示吗?我真的被困住了。
解决方案
刚刚找到的解决方案:
private List<GoldRate> goldRateList
应该与它所引用的 XML 元素的名称完全相同,因此正确的是:
private List<GoldRate> GoldPrice
推荐阅读
- android - FireMonkey Android:引发异常类 EJNIException 并带有消息'java.lang.IndexOutOfBoundsException:setSpan(XX ... XX)超出长度 X
- c++ - 在 C++ 中,如何将字符串数组的元素分配给 char 数组?
- firebase - 从 Firestore 中检索图像
- swift - 每次触发时向 Swift 计时器传递不同的参数
- laravel - 如何通过 laravel 中的代码也将文件的扩展名发送到 gcloud 应用存储桶?
- python - 是否可以在 Plotly 中更改图例框的大小?
- listener - AWS CDK Python 将新的 ECS/Fargate 目标组添加到现有的应用程序负载均衡器 (ALB)
- firebase - 无法读取未定义的属性“部署”
- python - Python 和 Pandas:如何计算具有特定条件的列
- c# - 模型在 ASP.NET MVC 中回发时为空