2

I have a controller in Play Framework (2.5.4) managed by sbt.

userController.scala

package controllers

// import models.User
import com.neruti.User

import play.api._
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.functional.syntax._
import pdi.jwt._
import pdi.jwt.{JwtPlayImplicits, JwtSession}
import play.api.mvc.Controller

import java.time.LocalDate
import java.util.UUID


class UserProfileController extends Controller with JwtPlayImplicits {

  def putUserProfile = Action(parse.json) {request =>
    val userProfile: JsResult[User] = request.body.validate[User]

    userProfile.map {
      case user:User => Ok("Its good")
    }.recoverTotal{
      e=>BadRequest("Detected error" + JsError.toFlatJson(e))
    }
  }
}

Below is User model in another separate module(core) managed by Maven. A multi-module maven pattern.

User.scala

package com.neruti

import play.api.libs.json._
import play.api.data.validation.ValidationError
import play.api.libs.functional.syntax._

case class User(
   username: String,
   email: Option[String] = None
)

object User {
  implicit val userReads: Reads[User] =(
    (__ \ "username").read[String] and
    (__ \ "email").readNullable[String]
  )(User.apply _)

  implicit val userWrites: Writes[User] =(
    (__ \ "username").write[String] and
    (__ \ "email").writeNullable[String]
  )(unlift (User.unapply))
}

Issue is inside the userController.scala, it can't see implicit JSON reader&writer in scope.

userController.scala:44: No Json deserializer found for type com.neruti.User. Try to implement an implicit Reads or Format for this type.
[error]     val userProfile: JsResult[User] = request.body.validate[User]

Did import com.neruti.User._, doesn't import implicit methods.

However, if I uncommented import models.User, using models package inside play, it works.

Any advice is much appreciated.

Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
Cheng Ping Onn
  • 687
  • 1
  • 8
  • 17
  • I'm not sure I fully understand your code. Do you have two classes named `User`? One in `models` package, and the other in `com.neruti` package? – Paweł Jurczenko Nov 27 '16 at 12:38
  • Yes, the `models` package is for testing and verification that my code is working properly. For production, only `com.neruti` package will be used. – Cheng Ping Onn Nov 27 '16 at 12:43

1 Answers1

0

For some reason I can't comprehend, after I move Reads[T] and Writes[T] converters to another object, it works.

Cheng Ping Onn
  • 687
  • 1
  • 8
  • 17