使用DataContract序列化程序时,无法反序列化Id
值,如下例所示:
using System;
using System.Runtime.Serialization;
using System.Xml.Linq;
public class Program
{
private const string SAMPLE_VALIDATION_RESULT_XML = @" <ValidationResult>
<Message>The FooBar record has duplicate key values.</Message>
<Id>Microsoft.LightSwitch.EntityObject.DuplicateKey</Id>
<Target>http://localhost:55815/ApplicationData.svc/FooBar(0)</Target>
</ValidationResult>";
[DataContract(Name = "ValidationResult", Namespace = "")]
public class ValidationResult
{
[DataMember]
public string Message { get; set; }
[DataMember]
public string Id { get; set; }
[DataMember]
public string Target { get; set; }
}
public static void Main()
{
var doc = XDocument.Parse(SAMPLE_VALIDATION_RESULT_XML);
using (var reader = doc.CreateReader())
{
reader.MoveToContent();
var res = (new DataContractSerializer(typeof(ValidationResult))).ReadObject(reader) as ValidationResult;
Console.WriteLine($"res.Id = \"{res.Id}\", expected \"Microsoft.LightSwitch.EntityObject.DuplicateKey\"");
}
}
}
我猜测它与参照完整性功能有关,但我只找到一个选项来禁用它(在DataContractSerializer上),它不会影响结果。
我无法更改Id
字段的名称,因为它是第三方API,因此如何访问该值?
答案 0 :(得分:3)
指定成员的顺序
[DataContract(Name = "ValidationResult", Namespace = "")]
public class ValidationResult
{
[DataMember(Order = 0)]
public string Message { get; set; }
[DataMember(Order = 1)]
public string Id { get; set; }
[DataMember(Order = 2)]
public string Target { get; set; }
}
如果不指定订单,DataContractSerializer
期望成员按字母顺序排列。见Basic rules。很明显,服务提供商建立的订单。所以你必须指定它。
答案 1 :(得分:1)
请改用它。 XmlSerializer不关心订单。
var xml = new XmlSerializer(typeof(ValidationResult));
var res = (ValidationResult)xml.Deserialize(reader);