无法将Json解析为映射-Scala/Play
我无法解析作为映射得到的json。有人有什么想法吗?如果您需要更多信息,请务必询问。谢谢:) 正在尝试使用解析以下响应:无法将Json解析为映射-Scala/Play,json,scala,dictionary,playframework,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: Oe
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]
}
假设您有适当的
读取OepPoint
和ErrorMsg
的s。你可以做以下事情
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 )
}
Play-json为常见类型提供了Read
s,例如String
、Int
、List[A]
等。对于List[A]
等泛型类型,将需要A
的隐式读取。您必须为自己的类型提供implicit
Read
s。可能是OepPoint
和ErrorMsg
。我假设我定义OepPoint atm的方式是错误的case类OepPoint(oep:Double,loss:Double)对象OepPoint{implicit val oepPointReads=Json.format[OepPoint]}
只需为Json结构定义一个Read
<代码>作为[Map[String,或者[List[ErrorMsg],Seq[OepPoint]]]
即使提供了对ErrorMsg
和OepPoint
的正确读取,也不起作用。您能提供这些类的结构吗?play json库也不知道如何将某些内容解析为[A,B]
,因此您必须自己创建该逻辑。