[SalesForce] Why is SelectOption not supported by JSON class?

Here's the code:

List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('One', 'One'));
options.add(new SelectOption('Two', 'Two'));
System.debug(LoggingLevel.INFO, '==========' + JSON.serialize(options));

The error:

System.JSONException: Apex Type unsupported in JSON:
System.SelectOption

Is there a way I can convert List<SelectOption> to some other data type before serializing it? in a way that when I deserialize I get it back as a List<SelectOption>?

Best Answer

I assume this is for some historical reason as it would be convenient if it did work.

Instead you can create your own simple Apex class and convert to that:

public class SerializableSelectOption {

    public String value {get; set;}
    public String label {get; set;}

    public SerializableSelectOption(SelectOption so) {
        this.value = so.getValue();
        this.label = so.getLabel();
    }

    public SerializableSelectOption(PicklistEntry pe) {
        this.value = pe.getValue();
        this.label = pe.getLabel();
    }

    public SerializableSelectOption(String value, String label) {
        this.value = value;
        this.label = label;
    }
}

or just create a Map per SelectOption and convert to that:

SelectOption so = ...;

Map<String, String> sso = new Map<String, String>{
   "value" => so.getValue(),
   "label" => so.getLabel()
};