0

Using json4s, what is best practice to deserialize JSON to Scala case class (without index-key)?

some.json
{
  "1": {
    "id": 1,
    "year": 2014
  },
  "2": {
    "id": 2,
    "year": 2015
  },
  "3": {
    "id": 3,
    "year": 2016
  }
}

some case class case class Foo(id: Int, year: Int)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
sh0hei
  • 51
  • 6

1 Answers1

1

You should deserialize your json to corresponding scala data structure. In your case the type is Map[Int, Foo]. So extract this type first. The helping snippet is:

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

implicit lazy val formats = DefaultFormats
val json =
  """
    |{
    |  "1": {
    |    "id": 1,
    |    "year": 2014
    |  },
    |  "2": {
    |    "id": 2,
    |    "year": 2015
    |  },
    |  "3": {
    |    "id": 3,
    |    "year": 2016
    |  }
    |}
  """.stripMargin
case class Foo(id: Int, year: Int)

val ast = parse(json)
val fooMap = ast.extract[Map[Int, Foo]]

Result:

Map(1 -> Foo(1,2014), 2 -> Foo(2,2015), 3 -> Foo(3,2016))
Nikita
  • 4,435
  • 3
  • 24
  • 44