How to convert an object to a salesforce list class?

895    Asked by DipikaAgarwal in Salesforce , Asked on May 12, 2023
 I have an object with value (s1,s2,s3,s4) (this is the value I get during System.debug). Now I want to convert these values to a list of strings, i.e ['s1','s2','s3','s4'].
How can I do that?

I tried,

List test = new List(); test.addAll((List)obj); // threw an error can't convert List to List
List test = new List(); test.addAll((List) JSON.deserializeUntyped(obj.toString())); // throws Unexpected character ('(' (code 40)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]
Answered by Fiona Dickens

Unfortunately apex doesn't handle list-level type conversion so if "obj" is a List and even if each Object is actually a String you still cannot convert that salesforce list class directly to a List via type casting.

You have two options. First is to do a loop:
List obj = ...; List objAsStrings = new List(); for (Object value : obj) { objAsStrings.add((String) value); }
Or you can try serialising and deserializing via JSON:
objAsStrings = (List) JSON.deserialize(JSON.serialize(obj), List.class);
Both will fail if not all entries in the obj are strings (the JSON approach will be more permissive, only failing with numeric and Boolean entries, since many other types are still expressed as string-like in JSON).

Both are relatively expensive, CPU wise, but the JSON approach costs more CPU time for smaller arrays. It wins when you get to large arrays.



Your Answer