Skip to content

Instantly share code, notes, and snippets.

@dmitric
Created September 28, 2011 19:21
Show Gist options
  • Save dmitric/1248933 to your computer and use it in GitHub Desktop.
Save dmitric/1248933 to your computer and use it in GitHub Desktop.
CSVBeanBuilder
class CSVBeanBuilder {
public static final Closure STRING_TO_DOUBLE = { token ->return Double.parseDouble(token)}
public static final Closure STRING_TO_INT = { token ->return Integer.parseInt(token)}
public static final Closure STRING_TO_DATE = { token -> return new Date(java.sql.Date.valueOf(token).time)}
def static loadAs(Class clazz, String csv, conversions){
def results = []
def headers = [:]
csv.eachLine { line, lineNumber ->
if (lineNumber == 0){ //if we are on the first line, map all the headers to the column they appear in
line.split(",").eachWithIndex { prop, i ->
headers[prop] = i
}
}else{
def values = line.split(",")
if (values.size() == headers.size()){
def instance = clazz.newInstance() // create a new instance
//for each mapping, assign the value from the csv to the appropriate object property
conversions.each { conv ->
if (conv.containsKey("conversion")) // if there's a type conversion required, do it
instance[conv.classProperty] = conv.conversion.call(values[headers[conv.csvProperty]])
else
instance[conv.classProperty] = values[headers[conv.csvProperty]]
}
results << instance
}
}
}
return results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment