[SalesForce] Field output order when conver object to JSON

I need conver from a object to json in this order:

global class ResultDto {
    String ParlorCode;      // 1st
    String DepartmentCode;  // 2nd
    String EmployeeNumber;  // 3rd
    String Name;            // 4th
}

I return this object via custom rest API, or json.serialize this object to string,
the result is this, the field order is wrong:

{
  "ParlorCode" : "002895",
  "Name" : "Dev01",
  "EmployeeNumber" : null,
  "DepartmentCode" : "100091"
}

How can I get the specified order?
Any help would be appreciated.

Best Answer

By nature, JSON objects are unordered (just like maps in Apex or objects in Javascript). Whatever is consuming your JSON should not be order-dependent. However, this may be out of your control. If it is, you will need to use the JSON.createGenerator() method to build the JSON manually (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Json.htm#apex_System_Json_createGenerator). This will be incredibly more time consuming than using the standard serialization.