10

I came across the following code online:

@future(callout=true)
public static void runWarehouseEquipmentSync(){

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setMethod('GET');
    request.setEndpoint(WAREHOUSE_URL);
    HttpResponse response = http.send(request);

    if(response.getStatusCode() == 200) {

        List<Object> jsonResponse = (List<Object>)JSON.deserializeUntyped(response.getBody());
        List<Product2> productList = new List<Product2>();

        for(Object ob : jsonResponse) {

            Map<String,Object> mapJson = (Map<String,Object>)ob;
            Product2 pr = new Product2();
            pr.Replacement_Part__c = (Boolean)mapJson.get('replacement');
            pr.Name = (String)mapJson.get('name');
            pr.Maintenance_Cycle__c = (Integer)mapJson.get('maintenanceperiod');
            pr.Lifespan_Months__c = (Integer)mapJson.get('lifespan');
            pr.Cost__c = (Decimal) mapJson.get('lifespan');
            pr.Warehouse_SKU__c = (String)mapJson.get('sku');
            pr.Current_Inventory__c = (Double) mapJson.get('quantity');
            productList.add(pr);
        }

        if(productList.size()>0)
            upsert productList;
    }        
}

What I've never seen before and can't find an explanation for is the syntax of parts such as these:

(List<Object>)JSON.deserializeUntyped(response.getBody())

(Map<String,Object>)ob

(Boolean)mapJson.get('replacement')

etc.

In other words, what does a data type in parentheses, followed by an instance of an object or a method, do?

What are the above three examples doing?

Does anyone know of any documentation for their syntax?

Thanks

21

This is called a type cast. Apex has what is called a strict, static typing discipline, which means that all variables and values have a type, and that type is declared for variables at the time of compilation of the code.

Type casting declares for the Apex compiler what type of value you expect to get back from a generic function, like JSON.deserializeUntyped(), or in some cases converts from one type to another.

Here's an example of the conversion aspect of a type cast. You cannot do

Id a = SOME_VALUE;

if (a.startsWith('006')) {

because Id has no startsWith method. Id can be casted to String, though, which does:

Id a = SOME_VALUE;

if (((String)a).startsWith('006')) {

Not all types of value can be casted to one another, however.

The cases you cite are all instances, not of conversion, but the case where the data type isn't known to the compiler. These values are of type Object because they're coming back from a generic JSON deserialization routine, which doesn't know what type of data it's deserializing beforehand. Using the type cast allows you to supply this information to the compiler so that you can use and manipulate these values.

| improve this answer | |
7

To add to David's answer, the casts in this case are following the pattern of the expected JSON structure and how JSON.deserializeUntyped converts from JSON to Apex types. It looks like the JSON has this structure:

[
    {"replacement": "...", "name": "...", ...},
    {...},
    {...}
]

A JSON array (the [ ]) is converted to an Apex list and a JSON object (the { }) is converted to an Apex map. The casts tell the compiler to expect these types.

| improve this answer | |
  • How would someone know which casts to write based on a known JSON structure? Inversely, how did you correctly decipher the structure based on the casts you saw in the code? – Gabriel Rivera Feb 26 '18 at 18:18
  • 2
    @GabrielRivera Its always List<Object> in Apex for a JSON array (or vice versa) and Map<String,Object> in Apex for a JSON object (or vice versa). Then other casts once you get down to an individual values in the objects. See e.g. json.org for how simple JSON syntax is meaning not many Apex constructs are needed. – Keith C Feb 26 '18 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.