Apex : convert object to a list

apexlistobject

I have an object with value (s1,s2,s3,s4) (this is the value I get during System.debug).
Now I want to convert this values to list of strings, i.e ['s1','s2','s3','s4'].

How can I do that?

I tried,

List<String> test = new List<String>();
test.addAll((List<String>)obj); // threw an error cant convert List<Any> to List<String>
List<String> test = new List<String>();
test.addAll((List<String>) 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]

EDIT:
In case you are wondering how I got the object.
The object is a list of strings I retrieved from the body during an API call, after converting to Map<String, Object> I get the above obj

Best Answer

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

You have two options. First is to do a loop:

List<Object> obj = ...;
List<String> objAsStrings = new List<String>();

for (Object value : obj) {
  objAsStrings.add((String) value);
}

Or you can try serializing and deserializing via JSON:

objAsStrings = (List<String>) JSON.deserialize(JSON.serialize(obj), List<String>.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.