名單

2017-01-19 22 views
0

我有如下圖所示,我使用JSON.NET序列化類/反序列化名單

public class Car 
{ 
    [JsonProperty(Order = 3)] 
    public int CarId {get; set;} 
    [JsonProperty(Order = 1)] 
    public string CarName {get; set;} 
    [JsonIgnore] 
    public int CarMfgDate {get; set} 
    [JsonProperty(Order = 2)] 
    public int CarCapacity {get; set;} 
} 

我需要在同所有的JSON可見屬性的列表按照上面類中的'JsonProperty'屬性定義的順序。所以,我希望列表初始化爲'Car'類,如下所示。

List<string> columns = GetOrderedJSONProperties(); 

Console.WriteLine(columns.Count); //Prints "3" 
Console.WriteLine(columns[0]); //Prints "CarName" 
Console.WriteLine(columns[1]); //Prints "CarCapacity" 
Console.WriteLine(columns[2]); //Prints "CarId" 

請幫我寫一下GetOrderedJSONProperties()方法。感謝所有的幫助!

回答

2

可以使用Linqs OrderBy功能爲:

var columns = typeof(Car).GetProperties() 
    .Where(p => p.GetCustomAttribute<JsonIgnoreAttribute>() == null) 
    .OrderBy(p => p.GetCustomAttribute<JsonPropertyAttribute>()?.Order) 
    .Select(p => p.Name).ToList(); 
+0

這個工作有一些變化。我已在下面粘貼更改後的代碼。 (p = G.CustomAttributes(typeof(JsonIgnoreAttribute),false)== null || p.GetCustomAttributes(typeof(JsonIgnoreAttribute),false).Length = = 0) .OrderBy(p =>((JsonPropertyAttribute [])p.GetCustomAttributes(typeof(JsonPropertyAttribute),false))[0] .Order) .Select(p => p.Name).ToList(); '。感謝您指點我正確的方向。上述警告我接受了這個答案。 – mantadt

+0

@lefou具有類型的屬性getter作爲擴展方法存在:https://msdn.microsoft.com/en-us/library/hh194292(v=vs.110).aspx – Nico

+1

感謝您的鏈接@Nico! – mantadt