ArrayList的序列化
定义一个ArrayList,存放Int,String等基本类型可以被序列化。
自定义一个类,也可以被序列化。
但是把类添加到ArrayList,序列化有点问题,后来发现需要制定ExtraType[]参数。
[WebMethod]
public string SerializeQuestionsByDatetime()
{
ArrayList questions = new ArrayList();
foreach (QuestionModel model in Questions.GetQuestionsByStateScoreOrDatetime(2, 12, 1, 1))
{
questions.Add(model);
}
Type[] extra = new Type[1];
extra[0] = typeof(QuestionModel);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList),extra);
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.Default);
xs.Serialize(tw, questions);
tw.Close();
return Encoding.Default.GetString(ms.ToArray());
}
反序列化的代码
public ArrayList DeserializeQuestionsByDatetime(string serQuestions, Type type, Type[] extratype)
{
XmlSerializer xs = new XmlSerializer(type, extratype);
StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(serQuestions)), System.Text.Encoding.Default);
return (ArrayList)xs.Deserialize(sr);
}
public string SerializeQuestionsByDatetime()
{
ArrayList questions = new ArrayList();
foreach (QuestionModel model in Questions.GetQuestionsByStateScoreOrDatetime(2, 12, 1, 1))
{
questions.Add(model);
}
Type[] extra = new Type[1];
extra[0] = typeof(QuestionModel);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList),extra);
MemoryStream ms = new MemoryStream();
XmlTextWriter tw = new XmlTextWriter(ms, Encoding.Default);
xs.Serialize(tw, questions);
tw.Close();
return Encoding.Default.GetString(ms.ToArray());
}
反序列化的代码
public ArrayList DeserializeQuestionsByDatetime(string serQuestions, Type type, Type[] extratype)
{
XmlSerializer xs = new XmlSerializer(type, extratype);
StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(serQuestions)), System.Text.Encoding.Default);
return (ArrayList)xs.Deserialize(sr);
}