Blog-01-03

PHOTO EMBED

Tue Jun 14 2022 15:03:03 GMT+0000 (UTC)

Saved by @Justus

// Get the JSON String, usually from a Web Service, but for executabillity I picked our example JSON
String jsonString = '{ "done" : true, "totalSize" : 10000, "records" : [ { "Id" : "0012z00000AVOkfAAH", "Name" : "Test Account - 00001"}, { "Id" : "0012z00000AVOmZAAX", "Name" : "Test Account - 10000" } ] }';

// Call the processing logic, but give our new flashy method as an argument this time
handleRecordProcessing(
	getObjectMapListFromTopLevelAttribute(
		(Map<String,Object>) JSON.deserializeUntyped(jsonString),
		'records'
	)
);

/**
 * Method that receives an untyped deserialized JSON response where one of the top level attributes
 * is a list of objects you needs to convert to Object maps (Map<String,Object>) in a memory efficient way
 * 
 * @param objectMap The type casted untyped JSON --> (Map<String,Object>) JSON.deserializeUntyped(jsonString);
 * @param attributeName the top level attributeName that represents a list of objects inside of the JSON
 * @return a list of object maps that are now usable in the code
 */
public static List< Map<String,Object> > getObjectMapListFromTopLevelAttribute(Map<String,Object> objectMap, String attributeName){
	
	// Create a list of Object Maps to store out output
	List<Map<String,Object>> outputList = new List<Map<String,Object>>();

	// Iterate the object list from the input map, note that we cast it in the loop
	for(Object obj : (Object[]) objectMap.get(attributeName)){
		
		// Validate that the object is actually an object and NOT a list
		// Cast the objects to Object Maps inside the add() methods parameter
		if(obj instanceof Map<String, Object>){
			outputList.add((Map<String,Object>) obj);
		}
	}

	// Return our lovely new list of objects maps that we can now use without having wasted valuable heap space
	return outputList;
}

/**
 * Some service method that does the magic that needs to be done to the records
 * Any processing will happen inside the loop
 */
void handleRecordProcessing(List<Map<String,Object>> objectMapsToProcess){
	for(Map<String,Object> objectMap : objectMapsToProcess){
		System.debug('Id: ' + objectMap.get('Id') + ' - Name:' + objectMap.get('Name'));
	}
}
content_copyCOPY