[SalesForce] How to deserialize json string to Apex

I have a requirement, where I have to select some value from multipicklist and then send this json response to the server.

There are 2 scenarios:

1st Scenario:
when we are selecting and de-selecting by clicking the multipicklist. The response goes in a array.
"country":["Arizona","Arkansas","Colorado"] as a List<String>

2nd scenario:

When we select and de-select values manually (no Clicking), the response goes like below:
"country":"Arizona;Arkansas; Colorado" as a Single string

    @RemoteAction
        global static String searchCountry(String jsonSearchCriteria) {

            try {
                CountrySearchCriteria crit = (CountrySearchCriteria)JSON.deserialize(    
                    jsonSearchCriteria, 
                    CountrySearchCriteria.class
                );

public class CountrySearchCriteria {

       public List<String> country;  

1st Scenario works perfectly, because in the countruSearchCriteria we are deserializing with List, but when it is coming as single string, then it is throwing below error.

You are trying decode an invalid JSON string, expected a List, but
found "Arizona;Arkansas; Colorado"

Is there any work around, where both scenario works perfectly?

Best Answer

If suppose your json data is in string named jsonData then you can do like

Map<String, Object> mapOfJSONData = null;
List<string> countryList= null;

    if(jsonData.contains(';')){   //for 2nd scenario
        mapOfJSONData = (Map<String, Object>) JSON.deserializeUntyped(jsonData);
        string countries =(string) mapOfJSONData.get('country');
        countryList= countries.split(';');
    }else{ //for 1st scenario
       // your logic for 1st scenario
    }
Related Topic