Created
July 23, 2015 14:53
-
-
Save felipehummel/5569dd69038142ce3bb5 to your computer and use it in GitHub Desktop.
json default field
This file contains hidden or 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
object JsonExtensions { | |
def withDefaultCreatedAt[T](base: Format[T]) = new Format[T]{ | |
def reads(json: JsValue): JsResult[T] = base.compose(JsonExtensions.withDefault("createdAt", DateTime.now())).reads(json) | |
def writes(o: T): JsValue = base.writes(o) | |
} | |
def withDefault[A](key:String, default:A)(implicit writes:Writes[A]) = | |
__.json.update((__ \ key).json.copyFrom((__ \ key).json.pick orElse Reads.pure(Json.toJson(default)))) | |
} | |
// ..... | |
// usage | |
implicit val userFmt = JsonExtensions.withDefaultCreatedAt(Json.format[User]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment