为什么序列化行为在monotouch中的模拟器和iPad设备上存在差异? 我已声明序列化行为是UTF-8,但是当从ipad设备向WCF服务发送序列化数据时,我跟踪消息,它变为ascii,为什么? (在模拟器中,UTF-8没问题)
模拟器中的跟踪/中文: < ?xml version =“1.0”encoding =“utf-8”? > ...
iPad设备中的跟踪/中文: < ?xml version =“1.0”encoding =“us-ascii”? > ...
顺便说一句,我使用静态方法手动序列化数据:XmlSerialize。
public static string XmlSerialize<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
public static T XmlDeserialize<T>(string xmlOfObject) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sr = new StreamWriter(ms, Encoding.UTF8))
{
sr.Write(xmlOfObject);
sr.Flush();
ms.Seek(0, SeekOrigin.Begin);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(ms) as T;
}
}
}
答案 0 :(得分:2)
您需要设置XmlSerializer
以使用utf-8:
var serializer = new XmlSerializer(typeof(MyClass));
using (var writer = new StreamWriter("file.path"))
{
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = false, Encoding = Encoding.UTF8 }))
{
serializer.Serialize(xmlWriter, myObject);
}
}
否则它将使用默认编码,无论发生什么情况。