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)