Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save leogrim/8aa2a66f8f1bce605034d0e51b8349ab to your computer and use it in GitHub Desktop.
Save leogrim/8aa2a66f8f1bce605034d0e51b8349ab to your computer and use it in GitHub Desktop.
Scala Macro Annotation by Martin Raison
val format = fields.length match {
case 0 => c.abort(c.enclosingPosition, "Cannot create json formatter for case class with no fields")
case 1 =>
// Only one field, use the serializer for the field
q"""
implicit val jsonAnnotationFormat = {
import play.api.libs.json._
Format(
__.read[${fields.head.tpt}].map(s => ${className.toTermName}(s)),
new Writes[$className] { def writes(o: $className) = Json.toJson(o.${fields.head.name}) }
)
}
"""
case _ =>
// More than one field, use Play's Json.format[T] macro
q"implicit val jsonAnnotationFormat = play.api.libs.json.Json.format[$className]"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment