2017-01-16 79 views
1

我是新來的斯卡拉,並試圖映射我的JSON到一個對象。我找到了jackson-scala模塊,但無法弄清楚如何使用它。一個小例子可能有幫助。使用Scala Jackson進行JSON反序列化?

val json = { "_id" : "jzcyluvhqilqrocq" , "DP-Name" : "Sumit Agarwal" , "DP-Age" : "15" , "DP-height" : "115" , "DP-weight" : "68"} 

我想這個到Person(name: String, age: Int, height: Int, weight: Int)

到現在我一直在用這個嘗試:

import com.fasterxml.jackson.databind.ObjectMapper 

Val mapper = = new ObjectMapper();  
val data = mapper.readValue(json, classOf[Person]) 

依賴我使用:

"com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.4" 

我失去了上什麼?

編輯:

[error] (run-main-4) com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of models.Person: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?) 
+0

我唔ld改爲推薦https://circe.github.io/circe/。不使用反射。 – Reactormonk

+0

錯誤消息表明您缺少默認構造函數(空)。 Jackson首先創建一個空對象,然後查看json結構中的所有屬性,並迭代設置它們到結果對象中。缺點是你也必須爲每個對象的屬性提供setter。 :(但根據Reactormock的建議,我還建議使用circe,因爲這提供了一種更爲慣用的反序列化方法(至少在scala中) – irundaia

+0

任何解決方案/建議/解決方法scala jackson本身? –

回答

4

爲了使其工作,你需要與對象映射到註冊DefaultScalaModule:

val mapper = = new ObjectMapper(); 
mapper.registerModule(DefaultScalaModule) 

此外,您還需要更新您的案例類,並提供傑克遜與財產名稱字段名稱綁定:

case class Person(@JsonProperty("DP-Name") name: String, 
        @JsonProperty("DP-Age") age: Int, 
        @JsonProperty("DP-height") height: Int, 
        @JsonProperty("DP-weight") weight: Int) 
+0

謝謝@MonteCristo –

相關問題