3

我有一个将任何对象序列化为 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 序列化程序,但是这个函数将不再是通用的。

有什么建议么?

4

1 回答 1

3

不幸的是,我没有看到一个简单的方法来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
}
于 2013-10-25T22:16:35.183 回答