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.
If I have a case class:
case class Person(name:String, age:Int) val person = Person("Fred", 65)
So from their github readme:
val mapper = new ObjectMapper() mapper.registerModule(DefaultScalaModule)
OK, now what...? How to I convert p to/from JSON?
DefaultScalaModule is a Scala object that includes support for all currently supported Scala data types. If only partial support is desired, the component traits can be included individually: val module = new OptionModule with TupleModule {} val mapper = JsonMapper.builder() .addModule(module) .build()
pjfanning commented on Feb 23, 2021. ScalaObjectMapper is a mixin for Jackson ObjectMapper that provides some helper functions that use Scala Manifests to implicitly access type information.
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
Give this a shot:
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)
EDIT
Just be sure to declare the Person
class as top level as it will not work otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With