Apex SOQL – How to Retrieve a String from a Query

apexexecute-anonymousquerysoqlunit-test

How can I retrieve data as a string from a SOQL query?

The code I have below gives an error: "System.ListException: List index out of bounds: 0"
If a run a check through Query Editor or even ExecuteAnonymous, I can see the data that I'm looking for exists.
The tests indicate that the list created by the SOQL query is not empty, but for some reason will not let me select the first value.

public class SurveyUtilityTest {
    static testMethod void testParse() {
        List<Survey__c> surList = [SELECT Name, Full_Survey_Response__c 
                                    FROM Survey__c WHERE Name = 'test' LIMIT 1];
        if (surList != null){
            String json = String.valueOf(surList[0].get('Full_Survey_Response__c'));
            System.Assert(json != null);                        
        } else {
            System.Assert(surList == null);
        }
    }
}

Best Answer

A query never returns a null result. If there are no values, the list will be empty, instead.

if(!surList.isEmpty()) {
  String jsonString = surList[0].Full_Survey_Response__c;
} else {
  // Do something here
}
Related Topic