在Scala中解析对jsonarray的请求 [英] Parse get request to jsonarray in Scala

查看:1310
本文介绍了在Scala中解析对jsonarray的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求 https://api.github.com/users 返回用户列表.如何在Scala中将其解析为json对象数组,以便我可以访问对象的字段,例如login,id,...

The request https://api.github.com/users returns a list of users. How can I parse it in Scala to array of json objects so I can access objects' fields, e.g., login, id, ...

推荐答案

您可以使用 sttp客户端进行http调用,然后环绕将json解码为scala对象.

you can use sttp-client to make http calls and circe to decode json to scala object.

val SttpVersion = "1.1.12"
val circeVersion = "0.9.3"

libraryDependencies ++= Seq(
  "com.softwaremill.sttp" %% "core" % SttpVersion,
  "com.softwaremill.sttp" %% "async-http-client-backend-future" % SttpVersion,

  "io.circe" %% "circe-core" % circeVersion,
  "io.circe" %% "circe-generic" % circeVersion,
  "io.circe" %% "circe-parser" % circeVersion
)

示例

object GetExample {

  import scala.concurrent.ExecutionContext.Implicits.global

  import com.softwaremill.sttp._
  import com.softwaremill.sttp.asynchttpclient.future._

  import io.circe._
  import io.circe.parser._

  implicit val backend = AsyncHttpClientFutureBackend()

  def main(args: Array[String]): Unit = {

    val usersResponse: Future[Response[String]] = sttp.get(uri"""https://api.github.com/users""").send()

    val users = usersResponse.map {
      case Response(Right(r), _, _, _, _) => parse(r).map { json =>
        val users: Option[Vector[Json]] = json.asArray.map(arr => arr.flatMap(_.\\("login")))
        users.getOrElse(Vector.empty[Json])
      }
      case Response(Left(l), _, _, _, _) => Vector.empty[Json]
    }

    println(users)
  }
}

如果尝试REPL,将得到以下结果

you will result as below if you try on REPL

scala>     val users = usersResponse.map {
     |       case Response(Right(r), _, _, _, _) => parse(r).map { json =>
     |         val users: Option[Vector[Json]] = json.asArray.map(arr => arr.flatMap(_.\\("login")))
     |         users.getOrElse(Vector.empty[Json])
     |       }
     |       case Response(Left(l), _, _, _, _) => Vector.empty[Json]
     |     }
users: scala.concurrent.Future[Serializable with Equals] = Future(<not completed>)

scala> users
res1: scala.concurrent.Future[Serializable with Equals] = Future(Success(Right(Vector("mojombo", "defunkt", "pjhyett", "wycats", "ezmobius", "ivey", "evanphx", "vanpelt", "wayneeseguin", "brynary", "kevinclark", "technoweenie", "macournoyer", "takeo", "Caged", "topfunky", "anotherjesse", "roland", "lukas", "fanvsfan", "tomtt", "railsjitsu", "nitay", "kevwil", "KirinDave", "jamesgolick", "atmos", "errfree", "mojodna", "bmizerany"))))

这篇关于在Scala中解析对jsonarray的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆