[SalesForce] Creating JSON body in http request

I am new to SF integration and I need to create a json body in my apex callout class for opportunity object. The json body includes field attributes from Account object which is parent to the opportunity object.

Expected JSON format:

{ "Id" : "00XXXXXXXXXXXXX", "StageName" : "Review", "AccountName" : "United Oil & Gas Corp." }

Code:

for (Opportunity opp: [SELECT id ,StageName, Account.Name  from Opportunity where id in: oppIdSet]){
            HttpRequest request = new HttpRequest();
            HttpResponse response = new HttpResponse();
            Http http = new Http();
            
            request.setEndpoint('Endpoint URL');
            request.setHeader('Content-Type','application/json'); 
            request.setMethod('GET');
            request.setBody(JSON.serialize(opp));
            system.debug('opp json' +JSON.serialize(opp));
            
            response = http.send(request);
            if (response.getStatusCode() == 200) {
                System.debug('Response-' + response);
            }
        }

The JSON output I get using the above code is:

{"attributes":{"type":"Opportunity","url":"/services/data/v50.0/sobjects/Opportunity/0060I00000UMTevQAH"},"Id":"0060I00000UMTevQAH","StageName":"Review","AccountId":"00128000011FD9hAAG","Account":{"attributes":{"type":"Account","url":"/services/data/v50.0/sobjects/Account/00128000011FD9hAAG"},"Id":"00128000011FD9hAAG","AccountName":"United Oil & Gas Corp."}

Best Answer

To get the exact format you want, you can use a custom class, or a map. Here's the Map example:

String jsonBody = JSON.serialize(
    new Map<String, Object> {
        'Id' => opp.Id, 
        'StageName' => opp.StageName, 
        'AccountName' => opp.Account.Name
    });

You could also do this with a custom class:

public class Wrapper {
    public Id Id;
    public String StageName, AccountName;
    public Wrapper(Opportunity opp) {
        Id = opp.Id;
        StageName = opp.StageName;
        AccountName = opp.Account.Name;
    }
}

Which you can then serialize:

String jsonBody = JSON.serialize(new Wrapper(opp));
Related Topic