2

i have a case class User with an Enum as one of its attributes

i want to convert this class into Json using Play-Json api but i am getting error here is my User class

case class User ( name : String= "", id : String = "", status : UserStatus = ACTIVE)

object User{

implicit val userFmt = Json.format[User]

}

UserStatus

 object UserStatus extends Enumeration {
    type  UserStatus = Value
         val ACTIVE , INACTIVE , BLOCKED , DELETED = Value

         implicit val statusFmt = Json.format[UserStatus]  
  }

it gives me following error in User class

No implicit format for UserStatus available

on this line

implicit val userFmt = Json.format[User]

and following error in UserStatus(enum)

No unapply function found

on this line

implicit val statusFmt = Json.format[UserStatus] 

please help me!

Carlos Vilchez
  • 2,774
  • 28
  • 30
M.Ahsen Taqi
  • 965
  • 11
  • 35

1 Answers1

3

You only needed a formatter for your enum. I have rewritten your example using this as a way to write the formatter:

  import play.api.libs.json._
    object UserStatus extends Enumeration {
      type  UserStatus = Value
      val ACTIVE , INACTIVE , BLOCKED , DELETED = Value
    }



    case class User ( name : String= "", id : String = "", status : UserStatus.UserStatus = UserStatus.ACTIVE)

    object User{
      implicit val myEnumFormat = new Format[UserStatus.UserStatus] {
        def reads(json: JsValue) = JsSuccess(UserStatus.withName(json.as[String]))
        def writes(myEnum: UserStatus.UserStatus) = JsString(myEnum.toString)
      }

      implicit val userFmt = Json.format[User]

    }

    println(Json.toJson(User("1", "2", UserStatus.ACTIVE)))
Community
  • 1
  • 1
Carlos Vilchez
  • 2,774
  • 28
  • 30
  • 1
    is there any way to add a formatter in parent class and use it in the child classes as well , plus if i have a trait and 4 5 child classes how can i ensure code reusability for these formatters? – M.Ahsen Taqi Sep 17 '15 at 09:12
  • I tried to use traits to store the formatters some time ago, and at the end it becomes messy. Currently I declare them in objects. And whenever you need the formatters of an object in another, you can just import them at the beginning of the object. What do you think? – Carlos Vilchez Sep 17 '15 at 13:01