我有一个存储自定义对象的ArrayList。我想将ArrayList序列化为字符串,以便将其保存在应用程序设置中。
这个问题看起来要解决它,但是在java中。而且我对XML并不聪明,所以有人可以提供帮助吗? Serialize an ArrayList of Date object type
我有我的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()
{
...
答案 0 :(得分:5)
我测试了您的代码,只要您的对象上有[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()
{
}
}
答案 1 :(得分:2)
我遇到了类似的问题,这个名为SharpSerializer的程序可以通过Nuget获得。它将非常容易地处理您的ArrayList,只需输入代码:
SharpSerializer mySerializer = new SharpSerializer();
mySerializer.Serialize(ArrayList, "filetosaveto.xml");
这是该网站的链接,它是免费的,所以不用担心支付任何费用: