Created
August 16, 2017 03:10
-
-
Save lloydmeta/b73542e1f529d2920dedafa4a5838d0f to your computer and use it in GitHub Desktop.
Play JSON formatter generater for NewType wrapper types
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 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