C#DataMember序列化器排序与预期相反

时间:2013-11-15 15:47:03

标签: c# serialization jsonserializer datamember datacontractjsonserializer

根据这篇文章,我希望在序列化为JSON时,我的基类中的字段位于字段列表的顶部。但是,我看到列表底部的字段。排序在实际类本身中是正确的,但不在层次结构中。

正在发生的事情是它在课堂上正确排序,它与我期望的完全相反。我希望基类首先将它们的字段序列化。我不想使用Order = X属性,因为我的对象中有太多字段。

这与此处描述的完全相反:

http://msdn.microsoft.com/en-us/library/ms729813(v=vs.110).aspx

[DataContract]
public class MyBase {
  [DataMember]
  public long Id { get; set; }
}

[DataContract]
public class MyChild : MyBase { 
  [DataMember]
  public string Field1 { get; set; }
  [DataMember]
  public string Field2 { get; set; }
  [DataMember]
  public string Field3 { get; set; }
}

[DataContract]
public class MySecondChild : MyChild { 
  [DataMember]
  public string SecondField { get; set; }
}

序列化MySecondChild实例时......

预期

{ 
    "Id": 1,        
    "Field1": "f1",
    "Field2": "f2",
    "Field3": "f3",
    "SecondField": "s1"
}

实际

{  
    "SecondField": "s1",      
    "Field1": "f1",
    "Field2": "f2",
    "Field3": "f3",
    "Id": 1
}

1 个答案:

答案 0 :(得分:0)

适合我:http://pastebin.com/PqBEHf6g

{"Id":1,"Field1":"f1","Field2":"f2","Field3":"f3","SecondField":"s1"}