4

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

0

1 Answer 1

6

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.

5
  • the 2nd option worked , thanks also object is not list of Object (as that would be easy)[for the first approach] , it's simply a object.
    – Akash Jain
    Commented Jan 21, 2022 at 12:52
  • 1
    Since this is working, "obj" must actually be a List<Object>. You can check by simply trying to cast: (List<Object>) obj and see if you get an exception.
    – Phil W
    Commented Jan 21, 2022 at 12:54
  • See the JSON untyped deserialization documentation for detail.
    – Phil W
    Commented Jan 21, 2022 at 12:55
  • yes , it's List<Object> but when i try for(Object o : obj) i get for should iterate over a collection maybe i should type cast first and then try?
    – Akash Jain
    Commented Jan 21, 2022 at 13:01
  • 1
    Just do for (Object value : (List<Object>) obj) instead.
    – Phil W
    Commented Jan 21, 2022 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .