json - 将任何 JSON 解析为 JValue 而不指定案例类

标签 json scala json4s

我尝试更好地解释。

我正在从 json 字符串解析 json 文件,例如:

[
 {
   "album": "The White Stripes",
   "year": 1999,
   "US_peak_chart_post": 55
 },
 {
   "album": "De Stijl",
   "year": 2000,
   "US_peak_chart_post": 66
 }
]

Seq[Album]:

import org.json4s._
import org.json4s.jackson.JsonMethods._
import scala.util.{Failure, Success, Try}

object AlbumsHandler{
    implicit val formats = DefaultFormats

    def extractAlbumsFromJsonFile(json: String): Seq[Album] = {

      val jValues: Try[JValue] = Try(parse(json))
      val albums: Seq[Album] = jValues.map(
        value => value.extract[Seq[Album]]
      ).getOrElse(Seq())

      albums
    }
}

通过提供专辑案例类作为“蓝图”:

case class Album(album: String, year: Int, US_peak_chart_post: Int)

有没有办法做我已经在做的同样的事情,从我的 JSON 中自动提取 Seq[Album],而无需指定 case 类 > 作为蓝图?

非常感谢

最佳答案

嗯,任何 JSON 对象都可以提取到 Map 中,任何 JSON 数组都可以提取到 Seq 中。但是,使用 Map[String, Any] 不太方便,而且没有比指定案例类来提取类型安全结构更简单的方法了。

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats

val json = """[
             | {
             |   "album": "The White Stripes",
             |   "year": 1999,
             |   "US_peak_chart_post": 55
             | },
             | {
             |   "album": "De Stijl",
             |   "year": 2000,
             |   "US_peak_chart_post": 66
             | }
             |]""".stripMargin

val map = parse(json).extract[Seq[Map[String, Any]]]
// map: Seq[Map[String,Any]] = List(Map(album -> The White Stripes, year -> 1999, US_peak_chart_post -> 55), Map(album -> De Stijl, year -> 2000, US_peak_chart_post -> 66))

关于json - 将任何 JSON 解析为 JValue 而不指定案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661090/

相关文章:

php - JSON/数组到 MySQL

Scala,树结构数据的解析器组合器

json - 如何使用带有 UTF-8 字符的 json4s 序列化 JSON?

java - Scala中获取Json头节点值

python - 将 NDArray 写入 JSON 和 .CV 文件

javascript - 如何修复转义的 JSON 字符串 (JavaScript)

iphone - Objective-C JSON 解析错误

arrays - 隐式类适用于所有 Traversable 子类,包括 Array

scala - 如何废弃 scala 类构造的样板?

json - 如何使用 scala 中的 json4s 库测试我为解析器创建的案例类是否正确?