Skip to content

Commit 6b6405a

Browse files
author
Will Palmeri
committed
treat Option as CollectionLike in ScalaObjectMapper
This will ensure that the custom OptionDeserializer is always used when deserializing Options. Right now when `List[Option[_]]` is deserialized, the Option class is treated as a "simple" type in the constructed `JavaType` and thus a generic JSON Deserializer is used rather than `OptionDeserializer`. Note that the new test will NOT pass until a jackson-databind dependency with FasterXML/jackson-databind#407 is used
1 parent 9a4dc0b commit 6b6405a

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/main/scala/com/fasterxml/jackson/module/scala/experimental/ScalaObjectMapper.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ trait ScalaObjectMapper {
6464
} else if(isCollectionLike(clazz)) {
6565
val typeArguments = m.typeArguments.map(constructType(_)).toArray
6666
if(typeArguments.length != 1) {
67-
throw new IllegalArgumentException("Need exactly 1 type parameter for iterable like types ("+clazz.getName+")")
67+
throw new IllegalArgumentException("Need exactly 1 type parameter for collection like types ("+clazz.getName+")")
6868
}
6969
getTypeFactory.constructCollectionLikeType(clazz, typeArguments(0))
7070
} else {
@@ -309,8 +309,9 @@ trait ScalaObjectMapper {
309309
}
310310

311311
private val ITERABLE = classOf[collection.Iterable[_]]
312+
private val OPTION = classOf[Option[_]]
312313
private def isCollectionLike(c: Class[_]): Boolean = {
313-
ITERABLE.isAssignableFrom(c)
314+
ITERABLE.isAssignableFrom(c) || OPTION.isAssignableFrom(c)
314315
}
315316

316317
}

src/test/scala/com/fasterxml/jackson/module/scala/experimental/ScalaObjectMapperTest.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,12 @@ class ScalaObjectMapperTest extends FlatSpec with ShouldMatchers {
196196
assert(result.isInstanceOf[collection.Map[_, _]])
197197
}
198198

199+
it should "read a option values from a JSON array" in {
200+
val result = mapper.readValue[List[Option[String]]](toplevelOptionArrayJson)
201+
result(0) should equal(Some("some"))
202+
result(1) should equal(None)
203+
}
204+
199205
// No tests for the following functions:
200206
// def readValue[T: Manifest](src: File): T
201207
// def readValue[T: Manifest](src: URL): T
@@ -208,5 +214,6 @@ class ScalaObjectMapperTest extends FlatSpec with ShouldMatchers {
208214
private val genericTwoFieldJson = """{"first":"firstVal","second":"secondVal"}"""
209215
private val genericMixedFieldJson = """{"first":"firstVal","second":2}"""
210216
private val toplevelArrayJson = """[{"t":42},{"t":31}]"""
217+
private val toplevelOptionArrayJson = """["some",null]"""
211218

212219
}

0 commit comments

Comments
 (0)