Scala: Parse JSON directly into a case class

后端 未结 7 2237
一生所求
一生所求 2020-12-24 11:36

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 seem

7条回答
  •  情深已故
    2020-12-24 12:15

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

提交回复
热议问题