简体   繁体   English

如何在Play中读取带有转义引号的JSON字符串

[英]How to read a JSON string with escaped quotes in Play

I'm receiving some JSON from a server: 我从服务器收到一些JSON:

"payload":"{\"action\":\"schedule\"}"

For why I am getting this odd looking JSON see this question . 为什么我得到这个奇怪的JSON看到这个问题 I've written some code to parse this bit of the object: 我写了一些代码来解析这个对象:

  implicit val botPayloadReads: Reads[BotPayload] = (
    (JsPath \ """\"action\"""").read[String] and
      (JsPath \ """\"returnToAction"""").readNullable[String]
    )(BotPayload.apply _)

But I am getting an error: 但我收到一个错误:

List((/entry(0)/messaging(0)/postback/payload/\"action\",List(ValidationError(List(error.path.missing),WrappedArray()))))

Which is a little weird because the path \\"action\\" is exactly what we are looking for. 这有点奇怪,因为路径“动作”正是我们正在寻找的。

The reason those quotes are escaped is that the "payload" key actually has the String type, so it contains a string representation of an object. 这些引号被转义的原因是"payload"键实际上具有String类型,因此它包含对象的字符串表示。 This is a very weird for a server to return, really. 真的,这对于服务器返回来说非常奇怪。 You will essentially need to re-parse the contents of payload 's value, or pre-process the JSON. 您基本上需要重新解析payload值的内容,或者预处理JSON。 This can all be done with Play's JSON API, though. 不过,这可以通过Play的JSON API完成。

import play.api.data.validation.ValidationError
import play.api.libs.json._
import scala.util.{ Success, Try }

case class BotPayload(action: String, returnToAction: Option[String])

object BotPayload {

  val payloadReads = Json.reads[BotPayload]

  implicit val reads: Reads[BotPayload] = Reads.StringReads
    .map(s => Try(Json.parse(s)))
    .collect(ValidationError("Cound not parse content of payload")) {
      case Success(js) => js
    }
    .andThen(payloadReads)

}

scala> val js = Json.parse(""" {"payload":"{\"action\":\"schedule\"}"} """)
js: play.api.libs.json.JsValue = {"payload":"{\"action\":\"schedule\"}"}

scala> (js \ "payload").validate[BotPayload]
res0: play.api.libs.json.JsResult[BotPayload] = JsSuccess(BotPayload(schedule,None),)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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