circe的 optics 模块几乎完全支持您要求的语法:
import io.circe.optics.JsonPath.root
val accountName = root.accounts.at(0).emailAccount.accountName.as[String]
然后,如果你有这个 JSON 值(我正在使用 circe 的 JSON 文字支持,但你也可以用io.circe.jawn.parse
(parse函数)解析一个字符串以获得Json
你正在使用的值):
import io.circe.Json, io.circe.literal._
val json: Json = json"""{
"accounts": [
{ "emailAccount": {
"accountName": "YMail",
"username": "USERNAME",
"password": "PASSWORD",
"url": "imap.yahoo.com",
"minutesBetweenChecks": 1,
"usersOfInterest": ["barney", "betty", "wilma"]
}},
{ "emailAccount": {
"accountName": "Gmail",
"username": "USER",
"password": "PASS",
"url": "imap.gmail.com",
"minutesBetweenChecks": 1,
"usersOfInterest": ["pebbles", "bam-bam"]
}}
]
}"""
您可以尝试像这样访问帐户名称:
scala> accountName.getOption(json)
res0: Option[String] = Some(YMail)
因为 circe-optics 是基于Monocle构建的,所以您可以获得其他一些不错的功能,例如不可变更新:
scala> accountName.modify(_.toLowerCase)(json)
res2: io.circe.Json =
{
"accounts" : [
{
"emailAccount" : {
"accountName" : "ymail",
...
等等。
更新:circe 被设计成模块化的,因此您只需“支付”您需要的部分。上面的示例期望类似于以下 SBT 设置:
scalaVersion := "2.11.8"
val circeVersion = "0.4.1"
libraryDependencies ++= Seq(
"io.circe" %% "circe-core" % circeVersion,
"io.circe" %% "circe-jawn" % circeVersion,
"io.circe" %% "circe-literal" % circeVersion,
"io.circe" %% "circe-optics" % circeVersion
)
…或者对于 Maven:
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-core_2.11</artifactId>
<version>0.4.1</version>
</dependency>
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-jawn_2.11</artifactId>
<version>0.4.1</version>
</dependency>
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-literal_2.11</artifactId>
<version>0.4.1</version>
</dependency>
<dependency>
<groupId>io.circe</groupId>
<artifactId>circe-optics_2.11</artifactId>
<version>0.4.1</version>
</dependency>