我一直在尝试将我的一个Java类保存到xml文件中,以便在重新运行我的应用程序时加载它,但是我得到了一个奇怪的结果。这是我要保存的课程:
public //public definition of a Song object
class Song implements Comparable, Serializable {
//fields
private StringProperty name;
public StringProperty artist;
public StringProperty album;
public IntegerProperty year;
public boolean emptySong;
//for serialization
private static final long serialVersionUID = 1738L;
//minimum constructor
public Song(){
this.emptySong = true;
}
public Song(String name, String artist){
this.name = new SimpleStringProperty(name);
this.artist = new SimpleStringProperty(artist);
}
//setter methods
public void setName(String name){
this.name = new SimpleStringProperty(name);
}
public void setArtist(String artist){
this.artist = new SimpleStringProperty(artist);
}
public void setAlbum(String album){
this.album = new SimpleStringProperty(album);
}
public void setYear(int i){
this.year = new SimpleIntegerProperty(i);
}
//getter methods
public String getName(){
return name.get();
}
public StringProperty nameProperty(){
return name;
}
public StringProperty getArtist(){
return artist;
}
public String getArtistString(){
return artist.get();
}
public StringProperty getAlbum(){
return album;
}
public String getAlbumString(){
if(album.get() != null){
return album.get();
}else{
return null;
}
}
public IntegerProperty getYear(){
return year;
}
public int getYearInt(){
return year.get();
}
@Override
public String toString() {
return name.toString();
}
@Override
public int compareTo(Object o) {
if (!(o instanceof Song)){
return -1;
}
String curr = name + "" + artist;
String comp = ((Song) o).getName().toString() + ((Song) o).getArtist().toString();
return curr.compareTo(comp);
}
}
这是我的保存方法:
public Songs songs;
public void saveSongDataToFile() {
try {
File file = new File("data/data.xml");
JAXBContext context = JAXBContext
.newInstance(SaveData.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our person data.
SaveData wrapper = new SaveData();
wrapper.setSongs(songs.songlist);
// Marshalling and saving XML to the file.
m.marshal(wrapper, file);
// Save the file path to the registry.
//setSongFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n");
e.printStackTrace();
alert.showAndWait();
}
}
但是我的输出文件正在保存没有艺术家,专辑或年份信息的数据。 所有元素都与此类似:
<song>
<artist/>
<album/>
<year/>
<emptySong>false</emptySong>
<name>Song 1</name>
</song>
我不确定为什么会这样。
编辑: 这是saveData类:
@XmlRootElement(name="songs")
public class SaveData {
private List<Song> songs;
@XmlElement(name="song")
public List<Song> getSongs(){
return songs;
}
public void setSongs(List<Song> songs){
this.songs = songs;
}
}
歌曲只是在saveSongDataToFile()方法上面的内存中声明。
答案 0 :(得分:0)
我发现问题所在,JAXB不知道如何处理StringProperty,所以它需要字符串,默认情况下,它将访问getter和setter属性。我把线放了
@XmlElement(name="artist")