2017-01-16 123 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 –

相关问题