Skip to content

Instantly share code, notes, and snippets.

@lloydmeta
Created August 16, 2017 03:10
Show Gist options
  • Save lloydmeta/b73542e1f529d2920dedafa4a5838d0f to your computer and use it in GitHub Desktop.
Save lloydmeta/b73542e1f529d2920dedafa4a5838d0f to your computer and use it in GitHub Desktop.
Play JSON formatter generater for NewType wrapper types
import play.api.libs.json._
object NewTypeJsonFormats {
/**
* Returns a Json Formatter for newtype wrappers
*
* Adapted from https://groups.google.com/d/msg/play-framework/zDUxEpEOZ6U/-7BpwI8iBCoJ
* Usage: NewTypeJsonFormats(UserId.apply)(UserId.unapply)
*/
def apply[I: Format, T](f1: I => T)(f2: T => Option[I]) = new Format[T] {
def reads(js: JsValue): JsResult[T] = js.validate[I] map f1
def writes(id: T): JsValue = Json.toJson(f2(id))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment