Repository navigation
FAQ
TL;DR: On Scala 3 with jackson-module-scala 3.3.0+, add derives ScalaTypeInfo to the case class (see below). Otherwise, use @JsonDeserialize(contentAs = classOf[java.lang.Integer]) or @JsonDeserialize(contentAs = classOf[Int]) on the offending member.
Scala, unlike Java, supports using primitive types as type arguments to generic classes. However, this is not supported by the JVM; there is no way to represent java.lang.List<int>, as an example. Prior to Scala 2.9, the compiler would represent Option[Int] as Option[java.lang.Integer] to the JVM, which would appear to naturally fall out of the requirement to use reference types as type parameters.
However, this led to significant problems, for example, implementing bridge methods for traits. The solution, for the time being, is that all primitive type parameters are represented as Object to the JVM. The Scala compiler uses the ScalaSignature annotation to determine what the Scala type needs to be in the cases where it matters.
Enter Jackson, which at its core is a Java library. The Scala module has informed Jackson that Option is effectively a container type, but it relies on Java reflection to determined the contained type, and comes up with Object. Jackson has rules for dealing with this situation, which dictate that the dynamic type of Object values should be the closest natural Java type for the value: java.lang.String for strings, java.lang.Integer, java.lang.Long, or java.math.BigInteger for whole numbers, depending on what size the number fits into, and similarly java.lang.Float, java.lang.Double, or java.lang.BigDecimal for floating point values.
The Scala compiler doesn't know what evil has been done in Java-land. It "knows" the value is a primitive int even if the JVM says Object, so it attempts to cast the value to the relevant boxed type and unbox it. If the primitive type matches the type selected by Jackson, it works; otherwise the actual type protests such treatment in the form of a ClassCastException.
See Related Projects. These extensions work with jackson-module-scala v2.13 and above.
These alternatives will work without issue.
- Option[BigInt]
- Option[java.lang.Integer]
The current workaround for this use case is to add the @JsonDeserialize annotation to the member being targeted (Java examples). Specifically, this annotation has a set of parameters that can be used for different situations:
-
contentAsfor collections or map values -
keyAsfor Map keys
Examples of how to use this annotation can be found in the tests directory.
For a class you cannot change, put the annotation on a Jackson mix-in with a member of the same name and register it on the mapper:
trait OptionLongMixin {
@JsonDeserialize(contentAs = classOf[Long]) def valueLong: Option[Long]
}
val mapper = JsonMapper.builder().addModule(DefaultScalaModule)
.addMixIn(classOf[OptionLong], classOf[OptionLongMixin]).build()Baeldung have some good Jackson docs. The docs focus on Java use cases but they should be usable for Scala use cases. They have one about registering a custom deserializer.
jackson-module-scala 2.13.1 adds ScalaAnnotationIntrospectorModule.registerReferencedType - that can be used if you can't annotate the class. (jackson-module-scala 2.13.0 had ScalaAnnotationIntrospector.registerReferencedType but this is now deprecated in favour of the newer method.
case class OptionLong(valueLong: Option[Long])
case class WrappedOptionLong(text: String, wrappedLong: OptionLong)
ScalaAnnotationIntrospectorModule.registerReferencedValueType(classOf[OptionLong], "valueLong", classOf[Long])
If you want to deserialize JSON to OptionLong or WrappedOptionLong, then this registerReferencedValueType will inform jackson-module-scala that valueLong is an optional Long - because jackson-module-scala currently can't infer this.
This the mechanism used under the hood by jackson-scala-reflect-extensions and jackson-scala3-reflection-extensions.
jackson-module-scala 3.3.0 (Jackson 3) adds tools.jackson.module.scala.ScalaTypeInfo, a Scala 3 type class that a case class can derive. The full type of each affected field is captured at compile time by a macro, so nothing needs to be registered with the mapper and no reflection extension is needed:
import tools.jackson.module.scala.ScalaTypeInfo
case class Erased(aLong: Option[Long], byId: Map[Long, String], pairs: Seq[(String, Long)]) derives ScalaTypeInfo
val mapper = JsonMapper.builder().addModule(DefaultScalaModule).build()
val read = mapper.readValue("""{"aLong":2,"byId":{"3":"x"},"pairs":[["a",4]]}""", classOf[Erased])
read.aLong.map(_ + 1L) // Some(3L)
read.byId.keys.map(_ + 1L) // Set(4L)
read.pairs.map(_._2 + 1L) // Seq(5L)A primitive is put back wherever it sits in the type: the content of an Option or a collection, the key or the value of a Map, a slot of a tuple or an Either, the argument of a generic case class, or any nesting of those - and for a public var or a @JsonCreator companion method's parameter as much as for a constructor parameter. Nothing is captured for Option[String], because a reference type argument survives in the generic signature and needs no help, or for a member that mentions a type parameter of the class, which Jackson resolves from the type it is asked to read.
Derive it on an enum or on the base of a sealed hierarchy and one clause covers every case or implementation (a derives cannot be written on an enum case):
enum Shape derives ScalaTypeInfo:
case Circle(radius: Option[Long])
case DotA class you cannot change is described by a Jackson mix-in that derives it. A trait extending the class describes the class's own members, so none is repeated; for a final class, which no trait can extend, a class with members of the same names (not necessarily all of them) does the same:
trait ErasedMixin extends Erased derives ScalaTypeInfo
val mapper = JsonMapper.builder().addModule(DefaultScalaModule)
.addMixIn(classOf[Erased], classOf[ErasedMixin]).build()What a mix-in derived is preferred to what the class itself derived, as a mix-in's annotations are preferred to the class's own.
A @JsonDeserialize annotation on a field, or on a mix-in, takes precedence over anything ScalaTypeInfo derived for it, as does a registerReferencedValueType call made by hand. It is Scala 3 only; the derives clause does not compile on Scala 2, where the reflection extensions or the annotation remain the options.