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

时间:2016-06-06 15:20:34

标签: json scala json4s

我试着更好地解释一下。

我正在从json String解析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作为“BluePrint”:

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

有没有办法做我正在做的同样的事情,从我的JSON中提取Seq[Album],但是自动,而不必指定case class作为蓝图?

非常感谢

1 个答案:

答案 0 :(得分:2)

好吧,任何JSON对象都可以被提取到Map中,任何JSON数组都可以被提取到Seq中。但是,使用Map[String, Any]并不太方便,并且没有办法比指定一个case类来提取类型安全结构更简单。

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))