Property order messed up when serializing JSON.NET

In my POCO objects, I often inherit from other POCO objects. When I serialize a POCO object using JSON.NET, the order of the properties gets messed up.

Let's say I have a Person class that looks like this:

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

Then I have an Employee class that inherits from the Person class:

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

When I serialize the Employee class, my JSON object looks like this:

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

Two questions:

  • Does the order of my properties of the JSON object know?
  • Even if the order of the properties does not matter, how can I make the properties be in the correct order, that is, I would like to see the properties of the Person class first, and then the properties of the Employee class.

Thank you for your help.

+8
json c # serialization
source share
2 answers

1.) No, the order does not matter.

2.) You can use the [JsonProperty (Order = x)] attribute to control the order:

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

From the quick test, the default order is 0, sorted from low to high, and properties with the same order value are sorted in random order.

+13
source share

Actually, since my object was already a JObject, I had to use the following solution:

 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); } } 

and then use it like this:

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

0
source share

All Articles