Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Small Example of Jackson Scala Module?

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?

like image 960
Greg Avatar asked Jun 06 '13 15:06

Greg


People also ask

What is DefaultScalaModule?

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()

What is ScalaObjectMapper?

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.

What is the use of Jackson ObjectMapper?

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.


1 Answers

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.

like image 68
cmbaxter Avatar answered Sep 20 '22 03:09

cmbaxter