我有一个将任何对象序列化为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序列化程序,但此功能将不再是通用的。
有什么建议吗?
答案 0 :(得分:2)
不幸的是,我没有看到让XmlSerializer
与JObject
一起使用的简单方法。我建议单独使用方法来处理这种情况:
private static string ConvertJObjectToXml(JObject jo, string rootElementName)
{
XmlDocument doc = JsonConvert.DeserializeXmlNode(jo.ToString(), rootElementName);
StringBuilder sb = new StringBuilder();
StringWriter sr = new StringWriter(sb);
XmlTextWriter xw = new XmlTextWriter(sr);
xw.Formatting = System.Xml.Formatting.Indented;
doc.WriteTo(xw);
return sb.ToString();
}
演示:
JObject jo = new JObject();
jo.Add(new JProperty("foo", "bar"));
jo.Add(new JProperty("fizz", "bang"));
string xml = ConvertJObjectToXml(jo, "root");
Console.WriteLine(xml);
输出:
<root>
<foo>bar</foo>
<fizz>bang</fizz>
</root>
如果您希望ConvertToXml()
方法能够处理所有对象,可以在顶部添加一行来检查obData
的类型,并根据需要委托给ConvertJObjectToXml()
:
private string ConvertToXml(object obData)
{
if (obData is JObject)
{
return ConvertJObjectToXml((JObject)obData, "root");
}
// process obData as normal using XmlSerializer
}