[英]How to deserialize json without index with json4s
Using json4s, what is best practice to deserialize JSON to Scala case class (without index-key)? 使用json4s,什么是将JSON反序列化为Scala case类的最佳实践(不带索引键)?
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. 您应该将json反序列化为相应的scala数据结构。 In your case the type is
Map[Int, Foo]
. 在您的情况下,类型为
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.