Неупорядочение XML с помощью JAXB возвращает исключение NullPointerException - PullRequest
0 голосов
/ 17 июня 2020

Я создал 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>

Я пытаюсь отключить дату и цену, но не могу войти во вложенные элементы - мой код возвращает исключение NullPointerException на unmarchaller ( ) метод. Вот мой код

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

Unmarchalling метод, который возвращает NullPointerException в System.out.println ()

    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;

}

Есть какие-нибудь подсказки по этому поводу? Я действительно застрял.

1 Ответ

0 голосов
/ 17 июня 2020

Только что найденное решение: private List<GoldRate> goldRateList должно называться точно так же, как элемент XML, на который он ссылается, поэтому правильное имя: private List<GoldRate> GoldPrice

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...