用于 Scala 2.12 的 JSON 解析器

问题描述

我正在寻找一种使用 JSON 解析器重写以下代码方法。目前使用的是已弃用的 scala.util.parsing.json.JSONObject

   val notebookInfo = Map("notebookURL" -> notebookURL,"user" -> user,"name" -> name,"mounts" -> dbutils.fs.ls("/mnt").map(_.path),"timestamp" -> System.currentTimeMillis)
  val notebookInfoJson = scala.util.parsing.json.JSONObject(notebookInfo)

我使用 Circe JSON 解析器尝试了以下操作,但出现错误

      val notebookInfo = Json.obj("notebookURL" -> Json.fromString(notebookURL),"user" -> Json.fromString(user),"name" -> Json.fromString(name),"mounts" -> Json.arr(Seq(dbutils.fs.ls("/mnt").map(Json.fromString) :_*),"timestamp" -> Json.fromLong(System.currentTimeMillis)))
  val notebookInfoJson = notebookInfo

以下是我看到的错误

 error: type mismatch;
 found   : String => io.circe.Json
 required: com.databricks.backend.daemon.dbutils.FileInfo => ?
                "mounts" -> Json.arr(Seq(dbutils.fs.ls("/mnt").map(Json.fromString) :_*),^
 error: type mismatch;
 found   : (String,io.circe.Json)
 required: io.circe.Json
                "timestamp" -> Json.fromLong(System.currentTimeMillis)))

解决方法

请通过this article。它有几个可以与 Scala 一起使用的 JSON 解析框架示例。

import net.liftweb.json.JsonAST
import net.liftweb.json.JsonDSL._
import net.liftweb.json.Printer.{compact,pretty}

object LiftJsonWithCollections extends App {

    val json = List(1,2,3)
    println(compact(JsonAST.render(json)))

    val map = Map("fname" -> "Alvin","lname" -> "Alexander")
    println(compact(JsonAST.render(map)))
}

该程序打印以下输出:

[1,3]
{"fname":"Alvin","lname":"Alexander"}

如果需要,还可以查看 this one 以从具有集合的 Scala 类创建 JSON 字符串。