我试着更好地解释一下。
我正在从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
作为蓝图?
非常感谢
答案 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))