简体   繁体   中英

Play! Scala JSON object handling

I'm getting back a JSON object from a third party API call. Let's say it looks like this:

{
  "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"
    }
  ]
}

I would like to iterate through the array and find the object that matches a certain width, height, and code, and return the href. I am still very new to Scala and would like some help. Thanks!

There are various ways to do it, such as this:

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

Here is the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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