2

我有一个可以随时间变化的 JSON,使用 case 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
4

1 回答 1

6

circe的 optics 模块几乎完全支持您要求的语法:

import io.circe.optics.JsonPath.root

val accountName = root.accounts.at(0).emailAccount.accountName.as[String]

然后,如果你有这个 JSON 值(我正在使用 circe 的 JSON 文字支持,但你也可以用io.circe.jawn.parseparse函数)解析一个字符串以获得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>
于 2016-04-19T16:53:23.750 回答