2014-10-15 12 views
9

Chciałbym użyć stałej wartości podczas konstruowania obiektu za pomocą odczytu JSON.Stała wartość w Scala Play JSON czyta

Na przykład klasa będzie:

case class UserInfo(
    userId: Long = -1, 
    firstName: Option[String] = None, 
    lastName: Option[String] = None 
) 

I read byłoby:

implicit val userRead: Reads[UserInfo] = (
     (JsPath \ "userId").read[Long] and 
     (JsPath \ "firstName").readNullable[String] and 
     (JsPath \ "lastName").readNullable[String] 
    )(UserInfo.apply _) 

Ale nie chcę mieć do określenia wartości dla identyfikatora użytkownika w obiekcie JSON. W jaki sposób chciałbym kodować odczyty tak, aby wartość -1 była zawsze tworzona w obiekcie UserInfo bez określania jej w odczytywanym obiekcie JSON?

Odpowiedz

9

Zastosowanie Reads.pure

implicit val userRead: Reads[UserInfo] = (
    Reads.pure(-1L) and 
    (JsPath \ "firstName").readNullable[String] and 
    (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _) 
0

Dzięki!

musiałem wykonać jedną niewielką zmianę, aby zmusić go do długiego:

implicit val userRead: Reads[UserInfo] = (
    Reads.pure(-1:Long) and 
    (JsPath \ "firstName").readNullable[String] and 
    (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _) 
Powiązane problemy