使用 Jackson 对 Scala 案例类进行(反)序列化 [英] Using Jackson to (De)-serialize a Scala Case Class
问题描述
我使用 Jackson 测试了 Scala 案例类的序列化.
I tested out the serialization of a Scala case class using Jackson.
DeserializeTest.java
public static void main(String[] args) throws Exception { // being lazy to catch-all
final ObjectMapper mapper = new ObjectMapper();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
mapper.writeValue(stream, p.Foo.personInstance());
System.out.println("result:" + stream.toString());
}
}
Foo.scala
object Foo {
case class Person(name: String, age: Int, hobbies: Option[String])
val personInstance = Person("foo", 555, Some("things"))
val PERSON_JSON = """ { "name": "Foo", "age": 555 } """
}
当我运行上述Java类的main
时,抛出了一个异常:
When I ran the above main
of the Java class, an exception was thrown:
[error] Exception in thread "main" org.codehaus.jackson.map.JsonMappingException:
No serializer found for class p.Foo$Person and no properties discovered
to create BeanSerializer (to avoid exception,
disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
我如何(反)序列化 Scala 案例类?
How can I (de)-serialize Scala case classes?
推荐答案
Jackson 希望您的类是 JavaBean,这意味着它希望该类的每个属性都具有 getX() 和/或 setX().
Jackson is expecting your class to be a JavaBean, which means its expects the class to have a getX() and/or setX() for every property.
选项 1
您可以使用注释 在 Scala 中创建 JavaBean 类BeanProperty.
示例
case class Person(
@BeanProperty val name: String,
@BeanProperty val age: Int,
@BeanProperty val hobbies: Option[String]
)
在这种情况下,val 意味着只定义了一个 getter.如果你想要反序列化的 setter,你可以将属性定义为 var.
In this case a val will mean only a getter is defined. If you want setters for deserialization you defined the properties as var.
选项 2
虽然选项 1 可以工作,但如果您真的想使用 Jackson,则有一些包装器允许它处理 Scala 类,例如 FasterXML 的 scala 模块 这可能是更好的方法.我没有使用它,因为我只是使用内置的 Json 库来播放.
While option 1 will work, if you really want to use Jackson there are wrappers that allow it to deal with Scala classes like FasterXML's scala module which might be a better approach. I haven't used it as I've just been using the Json library built in to play.
这篇关于使用 Jackson 对 Scala 案例类进行(反)序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!