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)
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.