数据合同序列化程序区分大小写
本文关键字:大小写 程序区 序列化 合同 数据 | 更新日期: 2023-09-27 18:34:45
我需要将原始xml反序列化为特定对象。但是,当涉及到布尔和枚举类型时,我遇到了问题,因为区分大小写完好无损。
public MyObjectTypeDeserializeMethod(string rawXML)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyObjectType));
MyObjectType tempMyObject = null;
try
{
// Use Memory Stream
using (MemoryStream memoryStream = new MemoryStream())
{
// Use Stream Writer
using (StreamWriter streamWriter = new StreamWriter(memoryStream))
{
// Write and Flush
streamWriter.Write(rawXML);
streamWriter.Flush();
// Read
memoryStream.Position = 0;
tempMyObject = (MyObjectType)serializer.ReadObject(memoryStream);
}
}
}
catch (Exception e)
{
throw e;
}
return tempMyObject;
}
public class MyObjectType
{
public bool boolValue {get; set;}
public MyEnumType enumValue {get; set;}
}
如果原始 XML 包含
<boolValue>true</boolValue>
它工作正常。但是,每当值与前一个值不同时,它就会引发异常,例如
<boolValue>True</boolValue>
如何解决此问题以允许从原始 XML 传递不区分大小写的布尔值和枚举值?
xml
规范将 xml 定义为区分大小写,并将布尔值定义为(注意大小写(文本true
和false
。 DataContractSerializer
做对了。如果值为 True
,则它不是 xml 布尔值,应被视为string
。
有很多方法可以解决这个问题。一个简单的方法是这种方法:
public class MyObjectType
{
[XmlIgnore] public bool BoolValue; // this is not mapping directly from the xml
[XmlElement("boolValue")]
public string BoolInternalValue // this is mapping directly from the xml and assign the value to the BoolValue property
{
get { return BoolValue.ToString(); }
set
{
bool.TryParse(value, out BoolValue);
}
}
...
我使用 XmlSerializer
来反序列化 xml:
public static T Deserialize<T>(string xmlContent)
{
T result;
var xmlSerializer = new XmlSerializer(typeof(T));
using (TextReader textReader = new StringReader(xmlContent))
{
result = ((T)xmlSerializer.Deserialize(textReader));
}
return result;
}