Salesforce: Read JSON Data in Apex class and map with object instance

//JSON Request/Body from the Server/External system
String response = '[ {  "name": "account1", "Phone": "12345", "Opportunities" : {records:[{ "name": "opportunity1", "StageName": "1 - Qualified Lead"},{ "name": "opportunity2", "StageName": "1 - Qualified Lead"}]} }, {  "name": "account1", "Phone": "12345" } ]';

//Parse the JSON Body into List of Object (Key with value)
List<Object> accountResponse = (List<Object>)JSON.deserializeUntyped(response);

Map<String, Object> jsonResponseOpportunityValues;
List<Account> AccountList = (List<Account>)JSON.deserialize(response, List<Account>.class);
List<Opportunity> OpportunityList = new List<Opportunity>();

//Read one by one list of object instance values to retrive the child object Instance values
for(Object AccountRecord : accountResponse) {  
    //Parse Individual object Instance into a map of field API name Key and values
    jsonResponseOpportunityValues = (Map<String, Object>) AccountRecord;

//Check weather request has child object Instance list of values is there or not, if it's there then read the list of child record values
if(jsonResponseOpportunityValues.containsKey('Opportunities')) {
OpportunityList.addAll((List<Opportunity>)JSON.deserialize(JSON.serialize(((Map<String, Object>)jsonResponseOpportunityValues.get('Opportunities')).get('records')), List<Opportunity>.class));
}
}

Comments

Popular posts from this blog

Transaction Security Policy In Salesforce

Salesforce Data Cloud

Add/Remove Content in the VF Page using JS