C# DataMember Serializer Ordering Opposite of Expected

三世轮回 提交于 2019-12-12 04:58:56

问题


According to this article, I'd expect to see the fields in my base class at the top of the list of fields when serializing to JSON. However, I'm seeing the fields at the bottom of the list. The ordering is correct within the actual class itself, but not among the hierarchy.

What's happening is it's ordering properly with the class, it it's doing the exact reverse of what I'd expect. I'd expect the base classes to have their fields serialized first. I don't want to use the Order=X attribute because there are too many fields in my objects.

This is the exact opposite behavior as described here:

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; }
}

When serializing an instance of MySecondChild...

Expected

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

Actual

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

回答1:


Works for me: http://pastebin.com/PqBEHf6g

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


来源:https://stackoverflow.com/questions/20004946/c-sharp-datamember-serializer-ordering-opposite-of-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!