我有一个将任何对象序列化为 xml 的函数。
private string ConvertToXml(object obData)
{
var x = new System.Xml.Serialization.XmlSerializer(obData.GetType());
var myStr = string.Empty;
try
{
using (var ms = new MemoryStream())
{
x.Serialize(ms, obData);
ms.Position = 0;
var sr = new StreamReader(ms);
myStr = sr.ReadToEnd();
_log.DebugFormat("Converted XML output of record:: {0}", myStr);
}
}
catch (Exception e)
{
_log.WarnFormat("Object Conversion to XML Document Failed ..{0} and the obData is: {1}", e.Message,obData) ;
}
return myStr;
}
它适用于我发送的任何类实例。但是当 JObject 进入此函数时,我收到以下错误:
System.InvalidOperationException: You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.
at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)
at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at CTP.Transformer.XSLT.XSLTTransformer.ConvertToXml(Object obData)
我可以使用 JObject 序列化程序,但是这个函数将不再是通用的。
有什么建议么?