2014-09-19 39 views
8

在我的POCO对象中,我经常继承其他POCO对象。当我使用JSON.NET序列化一个POCO对象时,属性的顺序变得混乱起来。由JSON.NET序列化时,属性顺序会搞乱

说,我有一个Person类,看起来像这样:

public class Person 
{ 
    public int Id {get; set;} 
    public string FirstName {get; set;} 
    public string LastName {get; set;} 
} 

然后,我有一个从Person类继承一个Employee类:

public class Employee : Person 
{ 
    public int DepartmentId {get; set;} 
    public string Title {get; set;} 
} 

当我序列Employee类,我JSON对象如下所示:

{ 
    "departmentId": 123, 
    "title": "Manager", 
    "id": 1234567, 
    "firstName": "John", 
    "lastName": "Smith" 
} 

两个问题:

  1. 我的JSON对象属性的顺序是否重要?
  2. 即使属性的顺序并不重要,我怎么能得到的属性是正确的顺序,即我想先看到Person类属性,然后是Employee类属性。

谢谢你的帮助。

回答

13

1.)不,订单无关紧要。

2.)可以使用[JsonProperty(订单= x)]的属性来控制的顺序:

public class Employee : Person 
{ 
    [JsonProperty(Order = 1)] 
    public int DepartmentId { get; set; } 

    [JsonProperty(Order = 1)] 
    public string Title { get; set; } 
} 

从快速测试,以便默认为0,从低排序到高,并且具有相同Order的值的属性按任意顺序排序。

+0

非常感谢! – Sam 2014-09-19 04:11:32

+0

如何使用字典? public class CountryInfo { public string Name {get;组; } public int IsEnabled {get;组; } } public class Countries { public Dictionary countriesInfo = new Dictionary (); } 我想根据countriesInfo.Name进行排序? – 2016-12-08 06:55:08

0

实际上,因为我的目标已经是一个JObject,我只好采用如下方案:

public class SortedJObject : JObject 
{ 
    public SortedJObject(JObject other) 
    { 
     var pairs = new List<KeyValuePair<string, JToken>>(); 
     foreach (var pair in other) 
     { 
      pairs.Add(pair); 
     } 
     pairs.OrderBy(p => p.Key).ForEach(pair => this[pair.Key] = pair.Value); 
    } 
} 

,然后用它是这样的:

string serializedObj = JsonConvert.SerializeObject(new SortedJObject(dataObject));