<?xml version="1.0" encoding="UTF-8"?>
<STATUS_UPDATE>
<UPDATES_COUNTER>2</UPDATES_COUNTER>
<LETTERS>
<LETTER>
<LETTER_KEY>key1</LETTER_KEY>
<STATUS>status1</STATUS>
</LETTER>
<LETTER>
<LETTER_KEY>key2</LETTER_KEY>
<STATUS>status2</STATUS>
</LETTER>
</LETTERS>
</STATUS_UPDATE>
So i have this xml. Im trying to create a pojo from it.
@XmlRootElement(name = "STATUS_UPDATE")
public class StatusUpdate {
private int updatesCounter;
List<Letter> letters;
public StatusUpdate(){
letters = new ArrayList<Letter>();
}
public StatusUpdate(int updatesCounter, List<Letter> letters){
super();
this.updatesCounter = updatesCounter;
this.letters = letters;
}
@XmlElement(name="LETTERS")
public List<Letter> getLetters() {
return letters;
}
public void setLetters(List<Letter> letters) {
this.letters = letters;
}
@XmlElement(name="UPDATES_COUNTER")
public int getUpdatesCounter() {
return updatesCounter;
}
public void setUpdatesCounter(int updatesCounter) {
this.updatesCounter = updatesCounter;
}
}
And letter class
@XmlRootElement(name = "LETTER")
public class Letter {
public Letter(){
}
public Letter(String letterKey,String status){
this.letterKey = letterKey;
this.status = status;
}
String letterKey;
String status;
@XmlElement(name="LETTER_KEY")
public String getLetterKey() {
return letterKey;
}
public void setLetterKey(String letterKey) {
this.letterKey = letterKey;
}
@XmlElement(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
and this code snipper wont seem to do the job. i get no errors, code runs, i get a 2 in my updateCounter variable, but my list is empty with only one letter object, with both variables null.
File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(StatusUpdate.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StatusUpdate msgObject = (StatusUpdate) jaxbUnmarshaller.unmarshal(file);
I've been reading the documentations and examples, but most of them are either written to match variable names and xml elemenets (which i dont want to) or are either not helpfull to me. Any ideas? I have a feeling i'm very close to my goal but i can't seem to grasp what i'm missing.
You need to add @XmlElementWrapper(name = "LETTERS")
annotation to getLetters()
method like this
@XmlElementWrapper(name = "LETTERS")
@XmlElement(name = "LETTER")
public List<Letter> getLetters() {
return letters;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.