If we want to serialize the object into its equivalent JSON along with maintaining order of its attribute
we can make use of a map with key as string and value as an object (can use any as per the requirement )
Note:
Put the key value in reverse order and after the JSON.serialize() you will get the JSON in the desired format
Example:
If we want the json for this class with attribute order maintained:
global class ResultDto {
String ParlorCode; // 1st
String DepartmentCode; // 2nd
String EmployeeNumber; // 3rd
String Name; // 4th
}
we can make use of map like below:
Map<String, Object> jsonObj = new Map<String, Object>();
// adding keys in reverse order
jsonObj.put('Name', 'some string text');
jsonObj.put('EmployeeNumber', 'some string text');
jsonObj.put('DepartmentCode', 'some string text');
jsonObj.put('ParlorCode', 'some string text');
String jsonOutput = JSON.serialize(jsonObj);
System.debug(jsonOutput);
Output:
{
"ParlorCode": "some string text",
"DepartmentCode": "some string text",
"EmployeeNumber": "some string text",
"Name": "some string text"
}