序列化对象的ArrayList

我有一个存储自定义对象的ArrayList。 我想将ArrayList序列化为字符串,以便将其保存在Application设置中。

这个问题看起来要解决它,但是在java中。 而且我对XML并不聪明,所以有人可以提供帮助吗? 序列化Date对象类型的ArrayList

我有我的ArrayList设置:

... MyObject tempObj = new MyObject("something",1,"something"); MyCollection.Add(tempObj); ... 

我最初有这个。 它输出字符串,但对象不存在:

  private string SerializeArrayList(ArrayList obj) { System.Xml.XmlDocument doc = new XmlDocument(); Type[] extraTypes = new Type[1]; extraTypes[0] = typeof(MyObject); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ArrayList), extraTypes); System.IO.MemoryStream stream = new System.IO.MemoryStream(); try { serializer.Serialize(stream, obj); stream.Position = 0; doc.Load(stream); return doc.InnerXml; } catch { throw; } finally { stream.Close(); stream.Dispose(); } } 

编辑:代码请求

  public class MyObject { private string eN; private Boolean bE; private int min; private Boolean bot; private string onE; public MyObject(string na, Boolean b) { ... } public MyObject() { } public string GetSomething() { ... 

我测试了你的代码,它似乎工作正常,只要你的对象上有[Serializable]

此外,如果您尝试序列化字段,则必须将它们设为公共属性。

我的测试:

  ArrayList array = new ArrayList(); Rules tempObj = new Rules { onE = "Value", min = 45, eN = "Value" }; array.Add(tempObj); string result = SerializeArrayList(array); private string SerializeArrayList(ArrayList obj) { XmlDocument doc = new XmlDocument(); XmlSerializer serializer = new XmlSerializer(typeof(ArrayList), new Type[]{typeof(Rules)}); using (MemoryStream stream = new System.IO.MemoryStream()) { try { serializer.Serialize(stream, obj); stream.Position = 0; doc.Load(stream); return doc.InnerXml; } catch (Exception ex) { } } return string.Empty; } 

宾语:

 [Serializable] [XmlType(TypeName = "Rules")] public class Rules { // Make fields propertys so they will be serialized public string eN { get; set; } //Name public Boolean bE { get; set; } //Whether blocked entirely public int min { get; set; } //Minutes they are allowed if blocked public Boolean bot { get; set; } //Create notification if allowance exceed public string onE { get; set; } //Nothing or CLOSE Process public Rules(string na, Boolean b) { } public Rules() { } } 

我遇到了类似的问题,有一个名为SharpSerializer的伟大程序,可以通过Nuget获得。 它将非常容易地处理您的ArrayList,只需键入代码:

  SharpSerializer mySerializer = new SharpSerializer(); mySerializer.Serialize(ArrayList, "filetosaveto.xml"); 

这是网站的链接,它是免费的,所以不用担心支付任何费用:

http://www.sharpserializer.com/en/index.html