CSVReader

CSVReader makes it easy to parse out raw strings that contain CSV-formatted data. CSV parsing can be deceptively difficult once you start getting into edge cases around commas, quotes, line breaks, etc, so this is a handy class to have around when you’re reading CSV data from External Systems.

The source code for this class is an adaptation of an open-source library from Marty Chang.

Definition

global static List<List<String>> readCSVData(String rawData); // defaults to using \n as the line ending character

global static List<List<String>> readCSVData(String rawData, String lineEnding);

Example Usage

// parse the response
List<List<String>> rows = valence.CSVReader.readCSVData(apiResponseBody);

// extract headers from first line of CSV data
List<String> headers = rows[0];

List<valence.RecordInFlight> records = new List<valence.RecordInFlight>();

// iterate over response records and create RecordInFlight instances from them
for(Integer i = 1, j = rows.size(); i < j; i++) { // deliberately start with i = 1 to skip the header row

        Map<String, Object> properties = new Map<String, Object>();

        for(Integer k = 0, l = headers.size(); k < l; k++) {
                properties.put(headers[k], rows[i][k]);
        }

        records.add(new valence.RecordInFlight(properties));
}