Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a json to an entity in Play Framework REST API

I am just starting up with scala and play framework and stuck on this seemingly simple problem.

I have a single REST end point to which I will post some Json Object. That Json Object needs to be converted to an entity.

The entity is declared of type case classes, and the received Json can be of any type of the case classes.

My problem is, I am unable to convert the Json to the corresponding entity type, because (as per the tutorial) I need to write implicit Reads in the validation with each of the fields defined.

For example

implicit val emailReads: Reads[Email] = (
    (JsPath \ "from").read[String] and
      (JsPath \ "subject").read[String]
    )(Email.apply _)

works fine for a sample case class email. But when I have case classes like this :

abstract class Event
case class OneEventType(type : String) extends Event
case class TwoEventType(type : String, attribute : SomeType) extends Event

And the controller method works on Event basis :

def events = Action(BodyParsers.parse.json) { request =>
    val eventReceived = request.body.validate[Event]
    //do something
    Ok(Json.obj("status" ->"OK"))
}

How would I validate the event and construct the correct Event Object, as in the Reads method I need to specify each of the fields ?

like image 687
gaganbm Avatar asked Dec 18 '25 12:12

gaganbm


1 Answers

This should work,

implicit val st: Reads[Event] = new Reads[Event] {
  def reads(json: JsValue): JsResult[Event] = {
    json match {
      case JsObject(Seq(("type", JsString(type)), ("attribute", JsString(attribute)))) =>  JsSuccess(TwoEventType(type, attribute))
      case o: JsObject if (o.value.get("type").isDefined) => JsSuccess(OneEventType(o.value.get("type")))
      case a: Any => JsError(a.toString())
    }
  }
}
like image 137
Johny T Koshy Avatar answered Dec 21 '25 02:12

Johny T Koshy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!