Serde = Serialization/Deserialization
Goals
- Evaluate Jackson Scala module's capability to serde case classes and collections in Scala
Jackson examples based on a scala trait hierarchy tree
- Root and intermediate nodes are traits
- Leaf nodes are case classes
- Root starts at level zero of the tree. The examples use a tree that is four levels deep
Tested on Jackson Scala module v2.9.5.
- Works out of the box with Scala types like
String
,Boolean
,Long
,BigDecimal
- Case classes are supported
- see
Money
- see
- Subtypes are supported, with additional configuration e.g.
@JsonTypeInfo(use = Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes(Array( new Type(value = classOf[A]), new Type(value = classOf[B]), new Type(value = classOf[C]) ))
- Write custom serializer/deserializer for sealed case objects, which is a way to define enumerations in Scala
- see
Weekday
- see
- Scala
Option
None
is serialized as JSON null- Configuration allows for other ways to handle
None
e.g. to omit the field in serialization - If value is present, only the value is serialized (without the
Option
wrapper)
- Scala collections
- Tuples and
Seq
are serialized as JSON array. Hence an empty tuple orSeq
is serialized as an empty array[]
- Supports tuples of mixed types
Map
is serialized as JSON object. Hence an emptyMap
is serialized as an empty object{}
- Tuples and
- Java 8's time package
java.time.*
requires additional dependency to serde in ISO string formatimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModule mapper.registerModule(new JavaTimeModule())
- General serde tips not specific to Jackson
- Prefer
BigDecimal
toDouble
/Float
because precision can be controlled
- Prefer
- Deserialize
Seq
works but notArray
- Tuple with Option elements can be serialized but deserialization will fail with
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of VALUE_NULL token
- Known issue that the
@JsonSerialize
annotation may not work at the attribute level