Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of properties get messed up when serialized by 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 properties gets all messed up.

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 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:

  1. Does the order of my JSON object properties matter?
  2. Even if the order of properties doesn't matter, how can I get the properties to be in correct order i.e. I'd like to see the Person class properties first, then the Employee class properties.

Thank you for your help.

like image 392
Sam Avatar asked Sep 19 '14 03:09

Sam


2 Answers

1.) No, order doesn't 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 a quick test, order defaults to 0, is sorted from low to high, and properties with the same value of Order are sorted in an arbitrary order.

like image 68
Frank Racis Avatar answered Nov 11 '22 08:11

Frank Racis


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

like image 45
Danny R Avatar answered Nov 11 '22 08:11

Danny R