Salesforce Apex JSON Sort Order

Salesforce Apex JSON Sort Order

JSONGenerator can be used if you want to order the JSON payload string.

Check the following apex code for reference. It will construct and manage the JSON pay string as per our requirements.

Sample Apex Code:

List < Account > listAccounts = [
SELECT Id, Name,
    (
        SELECT Id, Name
        FROM Opportunities
    ),
    (
        SELECT Id, Name
        FROM Contacts
    )
    FROM Account
    LIMIT 5
];
JSONGenerator gen = JSON.createGenerator(
    true
);
gen.writeStartObject();
gen.writeNumberField(
    'totalRecords',
    listAccounts.size()
);
gen.writeFieldName(
    'records'
);
gen.writeStartArray();
for ( 
    Account objAcc : listAccounts 
) {

    gen.writeStartObject();
    gen.writeStringField(
        'accountId', objAcc.Id
    );
    gen.writeStringField(
        'accountName', objAcc.Name
    );
    
    /* Contact Start */
    gen.writeFieldName(
        'contacts'
    );
    gen.writeStartArray();
    
    for ( 
        Contact objCon : objAcc.Contacts 
    ) {
        
        gen.writeStartObject();
        gen.writeStringField(
            'contactId', objCon.Id
        );
        gen.writeStringField(
            'contactName', objCon.Name
        );
        gen.writeEndObject();
    }
    
    gen.writeEndArray();    
    /* Contact End */
    
    /* Opportunity Start */
    gen.writeFieldName(
        'opportunities'
    );
    gen.writeStartArray();
    
    for ( 
        Opportunity objOpp : objAcc.Opportunities 
    ) {
        
        gen.writeStartObject();
        gen.writeStringField(
            'opportunityId', objOpp.Id
        );
        gen.writeStringField(
            'opportunityName', objOpp.Name
        );
        gen.writeEndObject();
    }
    
    gen.writeEndArray();    
    /* Opportunity End */
    
    gen.writeEndObject();

}
gen.writeEndArray();
gen.writeEndObject();
System.debug(
	gen.getAsString()
);

Output:

Leave a Reply