JsResultException - 无法成功解析json - 2.4x Play Scala

时间:2015-11-01 13:42:33

标签: json scala playframework-2.0

我有以下案例类;

import java.sql.Timestamp

case class Dose (date: Timestamp, ptHospitalNumber: String)

并在我的控制器中使用以下代码来处理json;

import play.api.libs.json._
import play.api.libs.functional.syntax._

  implicit val doseReads: Reads[Dose] = (
    (JsPath \ "date").read[Long].map(long => new Timestamp(long)) and
    (JsPath \ "ptHospitalNumber").read[String]
  )(Dose.apply _)

  def addDoses() = Action(BodyParsers.parse.json) { implicit request =>
    val doses = (request.body \ "doses" ).as[List[Dose]]
    //then iterate through the list and return json response
  }

然而,当发送json时(使用org.springframework.http.converter.json.MappingJackson2HttpMessageConverter从Android设备作为List [Dose]),我不断收到此错误;

  

play.api.libs.json.JsResultException:JsResultException(errors:List((,List(ValidationError)(List([{" date":1445789736831,   " hospitalNumber":" A059ES21"},{"日期":1445790530290," hospitalNumber":" A059ES21"}]不是对象),WrappedArray())))))

我也尝试了以下但是它返回了null;

    val dosesJsResult = (request.body \ "doses" ).validate[List[Dose]]
    val doses = dosesJsResult match{
      case s: JsSuccess[List[Dose]] => s.get
      case e: JsError => null
    }

我真的无法弄清楚我做错了什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

问题在于我试图找到一个名为" dose"在json中,但那并不存在。我需要做的就是将请求体解析为剂量列表;

implicit val doseDataReads = new Reads[Dose] {
  def reads(json: JsValue): JsResult[Dose] = {
    val date = (json \ "date").as[Long]
    val hospitalNumber = (json \ "hospitalNumber").as[String]
    JsSuccess(Dose(hospitalNumber, new Timestamp(date)))
  }
}

def addDoses() = Action(BodyParsers.parse.json) { implicit request =>
    val doses = request.body.as[List[Dose]]
    //rest of code to persist doses etc
}