【问题标题】:Play! Scala JSON object handling玩! Scala JSON 对象处理
【发布时间】:2019-03-18 04:41:56
【问题描述】:

我正在从第三方 API 调用中取回一个 JSON 对象。 假设它看起来像这样:

{
  "view": [{
      "width": "2100",
      "height": "1575",
      "code": "1",
      "href": "1.png"
    },
    {
      "width": "320",
      "height": "240",
      "code": "2",
      "href": "2.png"
    },
    {
      "width": "2100",
      "height": "1575",
      "code": "2",
      "href": "2.png"
    },
    {
      "width": "2100",
      "height": "1575",
      "code": "3",
      "href": "4.png"
    }
  ]
}

我想遍历数组,找到与某个宽度、高度和代码匹配的对象,并返回href。我对 Scala 还是很陌生,需要一些帮助。谢谢!

【问题讨论】:

  • 你在阅读文档后已经自己尝试过什么?
  • @cchantep 我已经尝试过模式匹配并尝试像在 JS 中那样映射它,但类型总是存在一些问题。我是 Typed 语言世界的新手,这真是令人沮丧的 atm
  • 请先阅读文档

标签: arrays json scala playframework functional-programming


【解决方案1】:

有多种方法可以做到这一点,例如:

import play.api.libs.json._

case class View(width: String, height: String, code: String, href: String)

object View { 
  implicit val viewFormat: Format[View] = Json.format[View] 
}

case class MyJsonObject(view: Seq[View])

object MyJsonObject { 
  implicit val myJsonObjectFormat: Format[MyJsonObject] = Json.format[MyJsonObject] 
}

val s = """{
  "view": [{
      "width": "2100",
      "height": "1575",
      "code": "1",
      "href": "1.png"
    },
    {
      "width": "320",
      "height": "240",
      "code": "2",
      "href": "2.png"
    },
    {
      "width": "2100",
      "height": "1575",
      "code": "2",
      "href": "2.png"
    },
    {
      "width": "2100",
      "height": "1575",
      "code": "3",
      "href": "4.png"
    }
  ]
}"""

def findMyHref(width: String, height: String, code: String): Option[String] = {
  for {
    myJsonObject <- Json.parse(s).asOpt[MyJsonObject]
    myView <- myJsonObject.view.find(v => v.width == width && v.height == height && v.code == code)
  } yield {
    myView.href
  }
}

findMyHref("2100", "1575", "2") //Some(2.png)

findMyHref("1", "2", "3") //None

这里是the documentation

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 2012-05-13
    • 2021-03-19
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多