Skip to content

Commit 1e486f4

Browse files
authored
Merge pull request #154 from pamidur/master
Added CSV sorting by JsonProperrtyAttribute.Order
2 parents 9a81b04 + c238253 commit 1e486f4

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

src/WebApiContrib.Core.Formatter.Csv/CsvOutputFormatter.cs

+13-8
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
using System;
1+
using Microsoft.AspNetCore.Mvc.Formatters;
2+
using Newtonsoft.Json;
3+
using System;
24
using System.Collections;
35
using System.Collections.Generic;
6+
using System.ComponentModel.DataAnnotations;
47
using System.IO;
58
using System.Linq;
9+
using System.Reflection;
610
using System.Text;
711
using System.Threading.Tasks;
8-
using System.Reflection;
9-
using Microsoft.AspNetCore.Mvc.Formatters;
10-
using System.ComponentModel.DataAnnotations;
11-
using Newtonsoft.Json;
1212

1313
namespace WebApiContrib.Core.Formatter.Csv
1414
{
@@ -53,7 +53,7 @@ private bool IsTypeOfIEnumerable(Type type)
5353

5454
return false;
5555
}
56-
56+
5757
/// <summary>
5858
/// Returns the JsonProperty data annotation name
5959
/// </summary>
@@ -96,7 +96,11 @@ public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext co
9696
{
9797
var values = useJsonAttributes
9898
? itemType.GetProperties().Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>(false).Any()) // Only get the properties that do not define JsonIgnore
99-
.Select(GetDisplayNameFromNewtonsoftJsonAnnotations)
99+
.Select(pi => new
100+
{
101+
Order = pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.Order ?? 0,
102+
Prop = pi
103+
}).OrderBy(d => d.Order).Select(d => GetDisplayNameFromNewtonsoftJsonAnnotations(d.Prop))
100104
: itemType.GetProperties().Select(pi => pi.GetCustomAttribute<DisplayAttribute>(false)?.Name ?? pi.Name);
101105

102106
await streamWriter.WriteLineAsync(string.Join(_options.CsvDelimiter, values));
@@ -110,8 +114,9 @@ public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext co
110114
.Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>().Any())
111115
.Select(pi => new
112116
{
117+
Order = pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.Order ?? 0,
113118
Value = pi.GetValue(obj, null)
114-
})
119+
}).OrderBy(d => d.Order).Select(d => new { d.Value })
115120
: obj.GetType().GetProperties().Select(
116121
pi => new
117122
{

0 commit comments

Comments
 (0)