我正在尝试C#序列化,并且不得不序列化一个Dictionary,因为它不能序列化,所以我使用了XML字符串,然后对它进行了反序列化(示例取自https://blogs.msdn.microsoft.com/adam/2010/09/10/how-to-serialize-a-dictionary-or-hashtable-in-c/)
DictionaryDataItem类:
[Serializable]
public class DictionaryDataItem
{
public string Key;
public string Value;
public DictionaryDataItem(string key, string value)
{
Key = key;
Value = value;
}
public DictionaryDataItem()
{
Key = "";
Value = "";
}
}
序列化代码:
[WebMethod]
public string ListarPaises()
{
List<DictionaryDataItem> Paises = new List<DictionaryDataItem>();
XmlSerializer serializer = new XmlSerializer(typeof(List<DictionaryDataItem>));
StringWriter sw = new StringWriter();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
try
{
Dictionary<string, string> diccionario = FabricaLogica.getLogicaGeneral().ListarPaises();
foreach (string key in diccionario.Keys)
{
Paises.Add(new DictionaryDataItem(key, diccionario[key]));
}
serializer.Serialize(sw, Paises, ns);
} catch (Exception ex)
{
ThrowSoapException(ex);
}
return sw.ToString();
}
序列化有效,它返回以下字符串作为xml:
<string xmlns="http://tempuri.org/">
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfDictionaryDataItem>
<DictionaryDataItem>
<Key>ARG</Key>
<Value>ARGENTINA</Value>
</DictionaryDataItem>
<DictionaryDataItem>
<Key>BRA</Key>
<Value>BRASIL</Value>
</DictionaryDataItem>
<DictionaryDataItem>
<Key>URU</Key>
<Value>URUGUAY</Value>
</DictionaryDataItem>
</ArrayOfDictionaryDataItem>
</string>
然后,我的反序列化代码:
Dictionary<string, string> Paises = new Dictionary<string, string>();
string RawData = new WebService.WebService().ListarPaises();
XmlSerializer xs = new XmlSerializer(typeof(List<DictionaryDataItem>));
StringReader sr = new StringReader(RawData);
List<DictionaryDataItem> templist = (List<DictionaryDataItem>)xs.Deserialize(sr);
foreach (DictionaryDataItem di in templist)
{
Paises.Add(di.Key, di.Value);
}
return Paises;
我可以看到templist
有3个项目,但是所有项目的键和值都为空。
我想念什么吗?