How to convert an object to a salesforce list class?
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,
Listtest = new List List(); test.addAll((List )obj); // threw an error can't convert List to 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]
Unfortunately apex doesn't handle list-level type conversion so if "obj" is a List
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.