本文介绍了通用XML序列化器,但无法在JObject上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将任何对象序列化为xml的函数.

I have a function which serializes any object into 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进入此函数时,出现以下错误:

It works fine for any class instance I send in. But when a JObject goes into this function, I get the following error:

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序列化程序,但是此函数将不再通用.

I can use a JObject serializer, but then this function will not be generic anymore.

有什么建议吗?

推荐答案

不幸的是,我没有一种简单的方法来使XmlSerializerJObject一起使用.我建议使用单独的to方法来处理这种情况:

Unfortunately I do not see an easy way to get the XmlSerializer to work with JObject. I would suggest making a separate to method to handle that case:

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():

If you want your ConvertToXml() method to be able to handle all objects, you can add a line at the top which checks the type of obData and delegates to ConvertJObjectToXml() as necessary:

private string ConvertToXml(object obData)
{
    if (obData is JObject)
    {
        return ConvertJObjectToXml((JObject)obData, "root");
    }

    // process obData as normal using XmlSerializer
}

这篇关于通用XML序列化器,但无法在JObject上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:49