序列化Date对象类型的ArrayList [英] Serialize an ArrayList of Date object type

查看:141
本文介绍了序列化Date对象类型的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要序列包含Date对象一个ArrayList,然后能够反序列化,并遍历反序列化版本。

I want to serialize an Arraylist containing Date objects and then be able to de-serialize it and iterate over the de-serialized version.

目前我有一个叫DateSerialize类实现Serializable。我有添加日期对象到ArrayList中,然后一旦做到这一点,我想序列化的方法。

Currently I have a class called DateSerialize that implements Serializable. I have a method for adding date objects into the arraylist and then once that is done i want to serialize it.

当我运行,我想反序列化ArrayList和获得相同的顺序和格式这些对象的计划,并希望在它运行的迭代器下一次。

Next time when i run the program i want to deserialize that arraylist and get those objects in the same order and format and want to run an iterator over it.

谁能帮我这个?

谢谢!

推荐答案

如果你想使用串行接口,你应该没有问题,因为ArrayList是序列化的,就像串,每一个基本类型。 公共类DateSerialize实现Serializable {} 应该做休息​​。你可以阅读更多有关此方法 >。但是也有很多的序列化的其他选项。所以,请更具体。

If you want to use Serializable, you should have no problems, because ArrayList is Serializable just as String and every primitive type. public class DateSerialize implements Serializable {} should do the rest. You can read more about this method here. However there are a lot of other options for serialization. So please be more specific.

ArrayList aList = new ArrayList();
MyBusinessObject obj = new MyBusinessObject();
obj.Name = "MyName";
obj.Address = "MyAddress";
obj.Phone = 435345;
aList.Add(obj);

二:序列化的ArrayList

/// <summary>
/// Serialize the ArrayList
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private string SerializeArrayList(ArrayList obj) { 
  System.Xml.XmlDocument doc = new XmlDocument();
  Type[] extraTypes = new Type[1];
  extraTypes[0] = typeof(MyBusinessObject);
  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(); 
  } 
}

第三:反序列化的ArrayList

/// <summary>
/// DeSerialize serialized string
/// </summary>
/// <param name="serializedData"></param>
/// <returns></returns>
private ArrayList DeSerializeArrayList(string serializedData) {
  ArrayList list = new ArrayList();
  Type[] extraTypes = new Type[1];
  extraTypes[0] = typeof(MyBusinessObject);
  System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ArrayList), extraTypes);
  XmlReader xReader = XmlReader.Create(new StringReader(serializedData));
  try {
    object obj = serializer.Deserialize(xReader);
    list = (ArrayList)obj;
  } catch { throw; } finally {
    xReader.Close();
  }
return list; 
}

这篇关于序列化Date对象类型的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆