Reputation: 101
I have a class as shown below and I am using JSON.NET to serialize/deserialize
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;}
}
I need to get a list of all Json-visible properties in the same order as defined by the 'JsonProperty' attribute in the class above. So, I would want the list to be initialized as below for the 'Car' class.
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"
Please help me write the GetOrderedJSONProperties() method. Thanks for all the help!
Upvotes: 0
Views: 130
Reputation: 3542
You can use Linqs OrderBy
function for that:
var columns = typeof(Car).GetProperties()
.Where(p => p.GetCustomAttribute<JsonIgnoreAttribute>() == null)
.OrderBy(p => p.GetCustomAttribute<JsonPropertyAttribute>()?.Order)
.Select(p => p.Name).ToList();
Upvotes: 2