Scala: Parse JSON directly into a case class

2019-02-01 18:13发布

Given a string of JSON, and a case class that corresponds to it, what's a simple way to parse the JSON into the case class? There are many libraries available, but it seems that Scala might now do this out of the box.

What about if the JSON should be parsed into a list of the case class?

UPDATE:

Jerkson seems to be abandoned, and I don't want to install the full Play or Lift framework or anything else heavy.

7条回答
放荡不羁爱自由
2楼-- · 2019-02-01 18:45

Use spray-json as it is small.

import spray.json._
import DefaultJsonProtocol._


val json = """{"one" : "1", "two" : "2", "three" : "3"}""".parseJson

case class Numbers(one: String, two: String, three: String)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val numbersFormat = jsonFormat3(Numbers)

}

import MyJsonProtocol._

val converted = json.convertTo[Numbers]

Download spray-json into sbt using this build.sbt:

lazy val root = (project in file(".")). settings( name := "jsonExample", libraryDependencies += "io.spray" %% "spray-json" % "1.3.2" )

查看更多
登录 后发表回答