gpt4 book ai didi

c# - Xml 序列化错误 : Unable to cast object of type

转载 作者:行者123 更新时间:2023-12-02 04:36:17 27 4
gpt4 key购买 nike

有人可以帮助我解决一个奇怪的序列化问题吗,我在一个环境中遇到它并且它在所有环境中都工作正常..但它在特定环境中失败了..所以我在这里指定为奇怪

代码

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

序列化的 XML 数据:

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

异常(exception)情况是:

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

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

最佳答案

此处的错误出在您未显示的 Serialize 方法中。您的 Deserialize 方法可以正常工作。以下 Serialize 方法工作正常:

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

如果我不得不猜测,您有以下内容:

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

如果您想要完全相同的输出而不需要不必要的 namespace 别名声明,请更改方法以包括:

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

编辑显示当前代码工作正常:

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

关于c# - Xml 序列化错误 : Unable to cast object of type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21901669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com