无法将Json解析为Map - Scala / Play

时间:2015-03-11 15:06:34

标签: json scala dictionary playframework

我无法解析我作为地图获得的json。有人有主意吗?如果您需要更多信息,请询问。谢谢:))

尝试使用以下方法解析以下响应:

Json.parse(response.body).as[Map[String, Either[List[ErrorMsg], Seq[OepPoint]]]]

响应:

{
  "Payout": {
    "errors":[
      {
        "field": "Last point: OepPoint(0.033,72.14). Current: OepPoint(0.033,65.71)",
        "message":"OEP must be unique"
      }
    ],
    "curve":[]
  }
}

抛出的错误消息是:

No Json deserializer found for type Map[String,Either[List[ErrorMsg],Seq[OepPoint]]]. Try to implement an implicit Reads or Format for this type.
[error]     val errorExpected = Json.parse(response.body).as[Map[String, Either[List[ErrorMsg], Seq[OepPoint]]]]
[error]                                                     ^
[error] one error found

OepPoint的结构:

case class OepPoint(oep: Double, loss: Double)

object OepPoint {
   implicit val oepPointReads = Json.format[OepPoint]
 }

ErrorMsg的结构:

case class ErrorMsg(field: String, message: String)

object ErrorMsg {
  implicit val errorMsgReads = Json.format[ErrorMsg]
}

1 个答案:

答案 0 :(得分:0)

假设ReadOepPoint适当ErrorMsg。你可以这样做。

case class ErrOrOep( errors: List[ ErrorMsg ], curve: List[ OepPoint ] )

implcit val errOrOepFormat = Json.format[ ErrOrOep ]

val jsonMap = Json.parse(response.body).as[ Map[String, ErrOrOep ] ]

val errOrOep = jsonMap( "Payout" )

val oepEither: Either[ List[ ErrorMsg ], List[ OepPoint ] ] = 
  ( errOrOep.errors, errOrOep.curve ) match {
    case ( _, h :: _ ) => Right( errOrOep.curve )
    case ( h :: _, _  ) => Left( errOrOep.error )
    case ( _, _ ) => Left( errOrOep.error )
  }