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." }


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');
            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."}
  • You just need to create a class and put the data into it.
    – sfdcfox
    Jan 27, 2021 at 12:58
  • @sfdcfox Can you please explain more may be with some sample code ?
    – SFDC IN
    Jan 27, 2021 at 13:21

1 Answer 1


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));
  • Thanks @sfdcfox for your time. You are always a great help
    – SFDC IN
    Jan 27, 2021 at 14:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .