Jackson Scala模块的小例子? [英] Small Example of Jackson Scala Module?
本文介绍了Jackson Scala模块的小例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能指出我的Scala模块2.10的杰克逊序列化/反序列化的简单例子吗?我正在寻找基于反射的JSON,不需要逐个字段的注释或赋值,它似乎可以做到这一点,但它们的文档中没有包含任何示例。
Can anyone point me towards a simple example of Jackson serialization/deserialization with their Scala module for 2.10? I'm looking for reflection-based JSON not requiring field-by-field annotation or assignment and it seemed this could do that, but their documentation includes no examples.
如果我有一个案例类:
case class Person(name:String, age:Int)
val person = Person("Fred", 65)
所以从他们的github自述文件:
So from their github readme:
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
好的,现在是什么......?如何将p转换为/从JSON?
OK, now what...? How to I convert p to/from JSON?
推荐答案
给这一点:
val person = Person("fred", 25)
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val out = new StringWriter
mapper.writeValue(out, person)
val json = out.toString()
println(json)
val person2 = mapper.readValue(json, classOf[Person])
println(person2)
编辑
请务必将 Person
类声明为最高级别否则不起作用。
Just be sure to declare the Person
class as top level as it will not work otherwise.
这篇关于Jackson Scala模块的小例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文