Resolved! Disable Alphabetical Sorting of JSON Attributes in Response from C sharp Service

JSON response received on the client side is generally in alphabetical order. This happens when we don’t add any sort order on our server-side API layers. In one of my project, there was a situation in which I wanted to add columns in Excel file from JSON response, as JSON attributes( In my case colum headers ) arranged in alphabetical, but I wanted them to be in some required order. I tried to do this client side in JS but it costs a lot! in term of page loading performance when data is large. As my services were in ASP.NET using C sharp so after some research, I tried something which worked like charm.


In the file, Sample_Def.cs added Order attribute in DataMember

Code Before change

    [Serializable, DataContract]
    public class BE_ServeSamlple
    {
        [DataMember]
        public Int32 EmpCode { get; set; }
        [DataMember]
        public String EmpName { get; set; }
        [DataMember]
        public String Division { get; set; }
        [DataMember]
        public String Department { get; set; }
        [DataMember]
        public String SkillType { get; set; }
       [DataMember]
        public String Designation { get; set; }

    }

 

Code After change

    [Serializable, DataContract]
    public class BE_ServeSamlple
    {
        [DataMember(Order=0)]
        public Int32 EmpCode { get; set; }
        [DataMember(Order = 1)]
        public String EmpName { get; set; }
        [DataMember(Order = 2)]
        public String Division { get; set; }
        [DataMember(Order = 3)]
        public String Department { get; set; }
        [DataMember(Order = 4)]
        public String SkillType { get; set; }
       [DataMember(Order = 5)]
        public String Designation { get; set; }

    }

 

Order should start with Order zero. After changes make sure to rebuild project to reflect changes.

This is just a quick help short tutorial. I hope this will be helpful πŸ™‚

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments