请求https://api.github.com/users返回用户列表。如何在Scala中将其解析为json对象数组,以便我可以访问对象的字段,例如login,id,...
答案 0 :(得分:2)
您可以使用sttp-client进行http调用,使用circe将json解码为scala对象。
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,您将得到以下结果
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"))))