[go: up one dir, main page]

Skip to content

seahrh/jackson-scala-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jackson-scala-example

Serde = Serialization/Deserialization

Goals

  1. Evaluate Jackson Scala module's capability to serde case classes and collections in Scala

tree_embed

google drawing

Jackson examples based on a scala trait hierarchy tree

  1. Root and intermediate nodes are traits
  2. Leaf nodes are case classes
  3. Root starts at level zero of the tree. The examples use a tree that is four levels deep
    1. see MyInheritanceTree

Tested on Jackson Scala module v2.9.5.

Notes

  1. Works out of the box with Scala types like String, Boolean, Long, BigDecimal
  2. Case classes are supported
    1. see Money
  3. 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])
    ))
    
  4. Write custom serializer/deserializer for sealed case objects, which is a way to define enumerations in Scala
    1. see Weekday
  5. Scala Option
    1. None is serialized as JSON null
    2. Configuration allows for other ways to handle None e.g. to omit the field in serialization
    3. If value is present, only the value is serialized (without the Option wrapper)
  6. Scala collections
    1. Tuples and Seq are serialized as JSON array. Hence an empty tuple or Seq is serialized as an empty array []
    2. Supports tuples of mixed types
    3. Map is serialized as JSON object. Hence an empty Map is serialized as an empty object {}
  7. Java 8's time package java.time.* requires additional dependency to serde in ISO string format
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
    
    mapper.registerModule(new JavaTimeModule())
  8. General serde tips not specific to Jackson
    1. Prefer BigDecimal to Double/Float because precision can be controlled

Limitations

  1. Deserialize Seq works but not Array
  2. 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
    
  3. Known issue that the @JsonSerialize annotation may not work at the attribute level

References

  1. Sealed case objects as enumerations in Scala
  2. Custom deserialization in Jackson
  3. json.org

Releases

No releases published

Packages

No packages published

Languages