Scala: Parse JSON directly into a case class

There are several frameworks which can exactly do that.

circe

Used a lot nowdays. Many great features. Will pull cats in.

https://circe.github.io/circe/ https://github.com/circe/circe

JSON4s

JSON4s is quite mature and supports jackson or a native JSON-Parser. Used it in many projects to replace jerkson.

https://github.com/json4s/json4s

play-json

Can be used without the full play stack. Great support as part of the play project at typesafe.

http://www.playframework.com/documentation/2.0/ScalaJson

Scala-Pickling

A serialization Framework. There is an option to serialize/ and deserialize to JSON.

https://github.com/scala/pickling

Spray JSON

Can searialize and deserialize. Need to know number of arguments for deserialization tough.

https://github.com/spray/spray-json


I've used https://github.com/json4s/json4s , only gripe so far is https://github.com/json4s/json4s/issues/137

import org.json4s._
import org.json4s.native.JsonMethods._

implicit val formats = DefaultFormats

case class ParsedPage(crawlDate: String, domain:String, url:String, text: String)

val js = """ {
"crawlDate": "20150226",
"domain": "0x20.be",
"url": "http://0x20.be/smw/index.php?title=99_Bottles_of_Beer&oldid=6214",
"text": "99 Bottles of Beer From Whitespace (Hackerspace Gent) Revision as of 14:43, 8 August 2012 by Hans ( Talk | contribs ) 99 Bottles of Beer Where: Loading map... Just me, with 99 bottles of beer and some friends. Subpages"
}"""


parse(js).extract[ParsedPage]

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