如何解析没有案例类的JSON Scala

时间:2016-04-19 16:19:47

标签: json scala parsing lift-json circe

我有一个可以随时间变化的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

1 个答案:

答案 0 :(得分:6)

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

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>