簡體   English   中英

玩! Scala JSON對象處理

[英]Play! Scala JSON object handling

我正在從第三方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還是很陌生,希望獲得一些幫助。 謝謝!

有多種方法可以做到這一點,例如:

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

這是文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM