Created
May 2, 2016 20:06
-
-
Save leogrim/8aa2a66f8f1bce605034d0e51b8349ab to your computer and use it in GitHub Desktop.
Scala Macro Annotation by Martin Raison
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
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