2014-09-06 2 views
1

나는 플레이 2.3.4를 사용하고, 나는 같은 간단한 모델 클래스를 정의했습니다 :Json 암시 적 읽기 : 형식이 일치하지 않습니다?

case class User(
    @Id 
    id: Int, 
    name: String 
) extends Model 

object User { 
    def find() = { /* some code here */} 
    implicit object UserFormat extends Format[User] { 
    def reads(json: JsValue) = User(
     (json \ "id").as[Int], 
     (json \ "name").as[String] 
    ) 

    def writes(user: User) = JsObject(Seq("id" -> id, "name" -> name)) 
    } 
} 

그리고 그것은 매우 간단합니다. 하지만 컴파일 오류가 발생합니다 :

Error:(31, -1) Play 2 Compiler: 
/Users/asheshambasta/code/finit/app/models/users/User.scala:31: type mismatch; 
    found : models.devices.User 
    required: play.api.libs.json.JsResult[models.users.User] 

내가 뭘 잘못하고 있니?

답변

2

위의 코드에는 몇 가지 문제점이 있습니다. 수신되는 컴파일 오류는 reads(json: JsValue)JsResult이고 이 아니고 모델을 반환해야하기 때문입니다. 이것은 Reads을 정의 할 때 실패를 설명해야하기 때문입니다. idnameuser.iduser.namewrites이어야합니다. 이것은 컴파일 : as[T]가 안전하지 때문에 JSON에 오류가있는 경우

object User { 

    implicit object UserFormat extends Format[User] { 
     def reads(json: JsValue) = JsSuccess(User(
      (json \ "id").as[Int], 
      (json \ "name").as[String] 
     )) 

     def writes(user: User) = Json.obj("id" -> user.id, "name" -> user.name) 
    } 
} 

그러나,이 예외가 발생합니다.

scala> val testJs = Json.parse("""{"id":"2", "name": "test"}""") 
testJs: play.api.libs.json.JsValue = {"id":"2","name":"test"} 

scala> testJs.validate[User] 
play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsnumber,WrappedArray()))))) 

Reads 정의 간단한 객체에 대해이 방법은 거의 항상 가치가 아니며, 더 나은 성취 JSON 콤비를 사용하여 할 수 있습니다.

object User { 
    implicit val reads: Reads[User] = (
     (__ \ "id").read[Int] and 
     (__ \ "name").read[String] 
    ) 

    implicit val writes: Writes[User] = (
     (__ \ "id").write[Int] and 
     (__ \ "name").write[String] 
    )  
} 

JSON 콤비는 코드의 첫 번째 조각처럼 예외를 발생하지 않으며, 유효성을 검사 할 때 그들은 JsResult에 모든 오류를 축적합니다. 이 같은 간단한 경우, JSON의 설립은 더 나은 것 :

object User { 
    implicit val format: Format[User] = Json.format[User] 
} 

또한 Reads하지만 Writes 또는 다른 방법으로 주위를 위해 뭔가 정의를해야하는 경우 Json.reads[T]Json.writes[T] 매크로가 있습니다.

+0

위대한 답변, 고마워요. 그것은 내 문제를 해결하고 또한 훨씬 더 명확하게 만드는 데 도움이됩니다. – Ashesh

관련 문제