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