【问题标题】:Unable to parse Json as a Map - Scala/Play无法将 Json 解析为地图 - Scala/Play
【发布时间】:2015-03-11 15:06:33
【问题描述】:

我无法解析作为地图获得的 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]
}

【问题讨论】:

  • 你能把东西格式化成更具可读性吗?
  • Play-json 为StringIntList[ A ] 等常见类型提供Reads。对于List[ A ] 等泛型类型,implicit Read 为@987654332 @ 将被要求。您必须为您自己的类型提供implicitReads。哪些是 - 可能是 OepPointErrorMsg
  • 我认为我定义 OepPoint atm 的方式是错误的? case class OepPoint(oep: Double, loss: Double) object OepPoint { implicit val oepPointReads = Json.format[OepPoint] }
  • 只需为您的 JSON 结构定义一个 Read。即使提供了对 ErrorMsgOepPoint 的正确读取,as[Map[String, Either[List[ErrorMsg], Seq[OepPoint]]]] 也无法工作。
  • 你能提供这些类的结构吗? play-json 库不知道如何将某些内容解析为 Either[A, B],因此您必须自己创建该逻辑。

标签: json scala dictionary playframework


【解决方案1】:

假设您有正确的Reads 用于OepPointErrorMsg。您可以执行以下操作。

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 )
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2021-05-13
    • 2014-07-20
    • 2017-09-07
    • 2016-11-20
    • 2016-07-12
    • 2012-01-03
    相关资源
    最近更新 更多