如何使用Xstream将arraylist转换为xml文件

时间:2022-05-26 06:45:37

Okay so here's my constructor

好的,这是我的构造函数

public class Highscore implements java.io.Serializable{

    public String name;
    public double score;
    protected Highscore (String na, double sc){
        name = na;
        score = sc;
    }
    public String getName(){
        return name;
    }
    public double getScore(){
        return score;
    }
    public String toString(){
        return name + "has "+score+" points.";

    }
}

Creating the object in my main class:

在我的主类中创建对象:

               Highscore ny = new Highscore (na, sc);
                allaHighscore.add(ny);

Then i want to save this object to be able to load them at a later point, this is for a highscore list for a game btw

然后我想保存这个对象,以便能够在以后加载它们,这是一个游戏的高分榜单btw

How do I proceed?

我该怎么办?

1 个解决方案

#1


2  

XStream is extremally trivial to use. You just create the serializer:

XStream使用起来非常简单。您只需创建序列化程序:

XStream xstream = new XStream();

With single call you can convert any object to string

通过单个调用,您可以将任何对象转换为字符串

String xml = xstream.toXML(myObject);

and do what you want with that String, eg. save to file.

并使用该String执行您想要的操作,例如。保存到文件。

Deserialization is also trivial

反序列化也是微不足道的

MyBean bean = (MyBean)xstream.fromXML(xml);

Works with POJO's, Java collections, etc.

适用于POJO,Java集合等。

#1


2  

XStream is extremally trivial to use. You just create the serializer:

XStream使用起来非常简单。您只需创建序列化程序:

XStream xstream = new XStream();

With single call you can convert any object to string

通过单个调用,您可以将任何对象转换为字符串

String xml = xstream.toXML(myObject);

and do what you want with that String, eg. save to file.

并使用该String执行您想要的操作,例如。保存到文件。

Deserialization is also trivial

反序列化也是微不足道的

MyBean bean = (MyBean)xstream.fromXML(xml);

Works with POJO's, Java collections, etc.

适用于POJO,Java集合等。