سؤال

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;
        }

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)

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

Any suggestions?

هل كانت مفيدة؟

المحلول

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();
}

Demo:

JObject jo = new JObject();
jo.Add(new JProperty("foo", "bar"));
jo.Add(new JProperty("fizz", "bang"));

string xml = ConvertJObjectToXml(jo, "root");
Console.WriteLine(xml);

Output:

<root>
  <foo>bar</foo>
  <fizz>bang</fizz>
</root>

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
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top