Created
April 19, 2017 14:26
-
-
Save onema/f7d670d714fd6fe6b6c964c1455d9d8a to your computer and use it in GitHub Desktop.
Converting a case class to a map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.{BufferedWriter, FileWriter} | |
import com.github.tototoshi.csv.CSVWriter | |
// ... | |
def writeCaseClasses(seqOfCaseClasses: Seq[AnyRef], filename: String): Unit = { | |
import Implicits._ | |
val mapOfKeyValues = seqOfCaseClasses.map(x => x.toMap) | |
val values = mapOfKeyValues.map(_.values.toSeq) | |
val header = mapOfKeyValues.head.keys.toSeq | |
val out = new BufferedWriter(new FileWriter(filename)) | |
val writer = new CSVWriter(out) | |
// Prepend the header to the values, alternatively you can use only the values | |
writer.writeAll(Seq(header) ++ value) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field | |
import org.apache.commons.lang3.StringEscapeUtils | |
/** | |
* Implicit class that provides a toMap method. It will turn a case class into a map of key, values. | |
* This is intended for case classes only. | |
*/ | |
object Implicits { | |
implicit class CaseClassToMap(c: AnyRef) { | |
// --- Methods --- | |
def toMap: Map[String, Any] = { | |
toMap(getDefaultValue) | |
} | |
def toMap(formatFunction: (Field, AnyRef) => Any): Map[String, Any] = { | |
(Map[String, Any]() /: c.getClass.getDeclaredFields) { (map: Map[String, Any], field: Field) => | |
field.setAccessible(true) | |
val fieldValue: Any = formatFunction(field, c) | |
map + (field.getName -> fieldValue) | |
} | |
} | |
def getDefaultValue(field: Field, c: AnyRef): Any = { | |
if (field.get(c) == null) { | |
// Set the default values to something other than null | |
if (field.getType.getName == "java.lang.String") "" | |
else if (field.getType.getName == "int") 0 | |
else if (field.getType.getName == "long") 0 | |
else if (field.getType.getName == "double") 0.0 | |
else if (field.getType.getName == "boolean") false | |
} else { | |
// Ensure that values are not HTML escaped | |
if (field.getType.getName == "java.lang.String") StringEscapeUtils.unescapeHtml4(field.get(c).toString) | |
else field.get(c) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment