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.

  • 2
    what is the use for order the fields? – Ratan Paul Dec 1 '15 at 11:06
  • 3
    From json.org "An object is an unordered set of name/value pairs." You should write your JSON processor so that order doesn't matter. – powlo Dec 1 '15 at 13:14

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.