0

I have a case in which we got some text-area fields that can have a list of String, Integer, and Decimal as a String.

for example, the field can have: 1111,2222,3333,4444,5555

another example, the field can have: 'Hi','Bye','Hello'

another example, the field can have: 44.5,133.5678,11.11

Is there a way to convert those values to a list of that type that got from the field in apex?

for example, if it was a string, I could create a List<String> and use split(',') to convert it into an iterable list.

Many thanks.

3
  • does each text area field correspond to a list of a specific type?
    – cropredy
    Jan 16, 2023 at 16:30
  • @cropredy we want to avoid the creation of three fields... so basically if this is possible, we want to convert the string into an unknown collection, check its type, and decide what to use. Thanks for you time
    – Salvation
    Jan 17, 2023 at 8:37
  • short answer - yes, you can use split() into a List<String> since the long textarea value is a String. Jan 17, 2023 at 15:14

1 Answer 1

2

So long as you know the type you want to convert to, you can use JSON by just wrapping the string in an array [...]:

Integer[] ints = (Integer[])JSON.deserialize('['+value+']', List<Integer>.class);
String[] strings = (String[])JSON.deserialize('['+value+']', List<String>.class);
Decimal[] decimals = (Decimal[])JSON.deserialize('['+value+']', List<Decimal>.class);

Note that JSON requires " instead of ' for quoted strings, so your strings might need to be: value.replaceAll('\'', '"');

3
  • Thanks @sfdcfox, but what if we have the same field that can be one of those three types? is there a way I can deserialize the string into an unknown list or other collection and then check its type and decide what to use?
    – Salvation
    Jan 17, 2023 at 8:27
  • 1
    @Salvation You can deserialize to a List<Object> with JSON.deserializeUntyped, but you'd have to inspect the individual items to see if they are then a String or Decimal (integers would also become Decimal values).
    – sfdcfox
    Jan 17, 2023 at 13:32
  • Thanks for your Help :)
    – Salvation
    Jan 17, 2023 at 14:47

You must log in to answer this question.

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