سؤال

Can some one help for a strange Serialization issue which I getting in a one environment and it working fine in all environments..but it failed a particular environment..so I specified as strange here

Code

public SomeType[] Deserialize(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(SomeType[]));
    StringReader stringReader = new StringReader(xml);
    SomeType[] types = (SomeType[])serializer.Deserialize(stringReader);
    stringReader.Close();
    return types;
}

Serialized XML data:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSomeType>
  <SomeType>
    <Field1>val</Field1>
    <Field2>val</Field2>
    <Field3>val</Field3>
  </SomeType>
</ArrayOfSomeType>
 

And the exception is:

System.InvalidCastException: Unable to cast object of type 'SomeType[]' to type 'SomeType'.

at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSomeType.Write11_SomeType(Object o)

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

المحلول

The error here is in the Serialize method that you don't show. Your Deserialize method works without error. The following Serialize method works fine:

static string Serialize(SomeType[] values)
{
    using (var sw = new StringWriter())
    {
        var serializer = new XmlSerializer(typeof(SomeType[]));
        serializer.Serialize(sw, values);
        return sw.ToString();
    }
}

If I had to guess, you have the following:

var serializer = new XmlSerializer(typeof(SomeType));

If you want the exact same output without unnecessary namespace alias declarations, change the method to include:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
serializer.Serialize(sw, values, ns);

Edit showing the current code working fine:

using System;
using System.IO;
using System.Xml.Serialization;

public class SomeType
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
}
public class MyTest
{
    public static SomeType[] Deserialize(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(SomeType[]));
        StringReader stringReader = new StringReader(xml);
        SomeType[] types = (SomeType[])serializer.Deserialize(stringReader);
        stringReader.Close();
        return types;
    }
    public static void Main()
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<ArrayOfSomeType>
   <SomeType>
      <Field1>val</Field1>
      <Field2>val</Field2>
      <Field3>val</Field3>
   </SomeType>
</ArrayOfSomeType>";
        var items = Deserialize(xml);
        foreach (var item in items)
        {
            Console.WriteLine("{0}, {1}, {2}",
                item.Field1, item.Field2, item.Field3);
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top