使用Jackson来(De) - 将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 } """
}
当我运行上面的 main
的Java类,抛出异常:
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) )
我如何(de)-serial化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
您可以创建JavaBean Scala中的类使用注释 BeanProperty 。
You can create JavaBean classes in Scala using the annotation 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来(De) - 将Scala案例类序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!