I am trying to create a dynamic query to csv class that will take any query and convert it to a csv and send it back to the caller. I would like to use keith-c's format logic because it's way cool and needed. BUT sobject.get('fieldname') returns back an Object.
I either need to cast it to the correct datatype or deal with it some how.
Any thoughts would be great, I don't want to create classes for every sobject type.
Thanks
public class ConvertToCsv {
public static Blob convert(CustomQuery.CustomQueryResult pResult) {
String csvFile;
List<String> tmpFieldList = new List<String>();
List<String> tmpRow = new List<String>();
for (String field :pResult.getFields()) {
tmpFieldList.add(ConvertToCsv.format(field));
}
csvFile = ConvertToCsv.line(tmpFieldList);
for (sObject row :pResult.getResults) {
for (String fieldKey :pResult.getFields()) {
tmpRow.add(ConvertToCsv.format(row.get(fieldKey)));
}
csvFile += ConvertToCsv.line(tmpRow);
tmpRow = new List<String>();
}
return Blob.valueOf(csvFile);
}
private static String line(String[] cells) {
return String.join(cells, ',') + '\n';
}
private static String format(Date d) {
return d != null ? '"' + d.format().escapeCsv() + '"' : '""';
}
private static String format(String s) {
return s != null ? '"' + s.escapeCsv() + '"' : '""';
}
private static String format(Decimal d, Integer scale) {
return d != null ? String.valueOf(d.setScale(scale)) : '';
}
private static String format(Decimal d) {
return format(d, 2);
}
}
instanceOf
help you here? As inif (row.get(fieldKey) instanceOf Date) tmpRow.add(ConvertToCsv((Date)row.get(fieldKey)) else if(row.get(fieldKey instanceOf Decimal) ...