简体   繁体   中英

2.3 Scala Play framework - Parse Json with embedded objects

the below code gives a compile error of

No implicit Reads for controllers.Inner available.

If I change

case class Outer (in : Inner)

to

case class Outer (in : String)

it'll compile fine, and I can parse both Outer and Inner json.

What is the best way to parse JSON with embedded object?

case class Outer (in : Inner)
object Outer {
  implicit val reads = Json.reads[Outer]
}


case class Inner (deep: String)
object Inner {
  implicit val reads = Json.reads[Inner]
}


object Test extends Controller {
  def tester = Action {
    implicit request =>


      val json = request.body.asJson.getOrElse(throw new InvalidRequest("No JSON found in request"))
      val validatedJSON = json.validate[Inner]


      Ok("")


  }
}

Thanks

Order is important.

case class Inner (deep: String)
object Inner {
  implicit val reads = Json.reads[Inner]
}

case class Outer (in : Inner)
object Outer {
  implicit val reads = Json.reads[Outer]
}

object Test extends Controller {
  def tester = Action {
    implicit request =>

      val json = request.body.asJson.getOrElse(throw new InvalidRequest("No JSON found in request"))
      val validatedJSON = json.validate[Inner]

      Ok("")

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM