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?)
我唔ld改为推荐https://circe.github.io/circe/。不使用反射。 – Reactormonk
错误消息表明您缺少默认构造函数(空)。 Jackson首先创建一个空对象,然后查看json结构中的所有属性,并迭代设置它们到结果对象中。缺点是你也必须为每个对象的属性提供setter。 :(但根据Reactormock的建议,我还建议使用circe,因为这提供了一种更为惯用的反序列化方法(至少在scala中) – irundaia
任何解决方案/建议/解决方法scala jackson本身? –