2015-08-03 52 views
0

使用json4s,將JSON反序列化爲Scala case類(不帶索引鍵)的最佳實踐是什麼?如何使用json4s反序列化沒有索引的json

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)

回答

1

你應該反序列化JSON的相應階的數據結構。在你的情況下,這種類型是Map[Int, Foo]。所以首先提取這種類型。該幫助片段是:

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]] 

結果:

Map(1 -> Foo(1,2014), 2 -> Foo(2,2015), 3 -> Foo(3,2016)) 
+0

它不應該是'地圖[字符串,富]'? –

相關問題