[英]How to serialize List<object>
I am writing common functions to serialize the given object and List<object> as follows 我正在编写常用函数来序列化给定对象和List <object>,如下所示
public string SerializeObject(Object pObject)// for given object
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
public string SerializeObject(List<Object> pObject)// for given List<object>
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
first one is working fine. 第一个工作正常。 If I pass any type, it is successfully returning xml string.
如果我传递任何类型,它会成功返回xml字符串。
CORRECTION: Compilation error has occurred for second one (Error: cannot convert from List<MyType>
to List<object>
. 更正:第二次出现编译错误(错误:无法从
List<MyType>
转换为List<object>
。
I rewrite the second one as follows which solves my problem. 我重写第二个如下解决了我的问题。 Now it is serializing the given
List<generic types>
. 现在它正在序列化给定的
List<generic types>
。
private string SerializeObject<T>(T source)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, source);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
string XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
https://weblogs.asp.net/rajbk/Contents/Item/Display/345 https://weblogs.asp.net/rajbk/Contents/Item/Display/345
The relevant code from the article: 文章中的相关代码:
private static string SerializeObject<T>(T source)
{
var serializer = new XmlSerializer(typeof(T));
using (var sw = new System.IO.StringWriter())
using (var writer = XmlWriter.Create(sw))
{
serializer.Serialize(writer, source);
return sw.ToString();
}
}
I have tried your two functions without much trouble. 我已经尝试了你的两个功能,没有太多麻烦。 The only thing I changed was this line:
我唯一改变的就是这一行:
XmlSerializer xs = new XmlSerializer(typeof(pObject));
to this: 对此:
XmlSerializer xs = new XmlSerializer(pObject.GetType());
typeof() requires an actual type whereas GetType() returns the type of the object. typeof()需要实际类型,而GetType()返回对象的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.