Declaration of Data Types Apex

apexdata-typesdeserialize

I'm a new learner in Apex and I have a question about declaration of variables(A map in this case) and its Data type.

I've been working with integrations and REST callouts and spend a long time when recieving the http response and trying to store it in a Map without using the second "Map<String, Object>" in the parentheses.

Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(httpResponse.getBody()); 

I solved it but I don't get what is this second writing of the map doing. Could someone explain this to me?

Best Answer

The (Map<String, Object>) bit is called type casting. It forces something of one type to be treated as if it were a different type.

In the case of JSON.deserializeUntyped(), the method returns a result of type Object, but that type is functionally useless to us. The method returns an Object because JSON can start as either a list or a map. Since there's no way to know which it'll be until you try to deserialize some JSON, Salesforce needs to use a return type that can cover both cases. In this case, the only thing that would work is the Object type.

To be able to access the deserialized data, we need to use some other type. The type cast to Map<String, Object> is basically us saying yes, I know this is technically an Object, but treat it as a Map<String, Object> instead, trust me on this.

Type casting only works if the types are compatible (i.e. one type is derived from the other).

  • You can cast an Account as an SObject (up-casting, since you're going from a more specific type (Account) to its less specific, parent type (SObject)).
  • You can also sometimes cast an SObject as an Account (down-casting, since you're changing to a more specific type).
  • You cannot type-cast between unrelated/incompatible types like String and Integer (though we can use Integer.valueOf() to convert a String to an Int, and use String.valueOf() to convert an Int to a String)