我有一个JSON,它可以随时间变化,用例class可能不可信,因为每次JSON更改时我都需要更改它的结构。
例如,如果我有这样的JSON:
val 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"]
}}
]
}"""
我能用之类的东西访问它吗
val parsedJSON = parse(json)
parsedJSON.accounts(0).emailAccount.accountName
circe的光学模块几乎完全支持您所要求的语法:
import io.circe.optics.JsonPath.root
val accountName = root.accounts.at(0).emailAccount.accountName.as[String]
然后,如果您有这个JSON值(我使用cire的JSON文本支持,但您也可以使用io.circe.jawn.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>