Sam Sam - 1 year ago 138
JSON Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download