0
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)

val original: Map[String, Option[String]] = Map[String, Option[String]]("key" -> Some("value"))

val json: ObjectNode = new ObjectNode(JsonNodeFactory.instance).put("key", "value")

val converted = mapper.convertValue(json, classOf[Map[String, Option[String]]])

println(s"JSON: $json")
println(s"original: $original")
println(s"converted: $converted, equals original " + (if (converted == original) "TRUE" else "FALSE"))

prints

JSON: {"key":"value"}
original: Map(key -> Some(value))
converted: Map(key -> value), equals original FALSE

What's the best way of deserializing into Map[String, Option[String]]?

Grega Kešpret
  • 11,827
  • 6
  • 39
  • 44
  • Can you give us an example of what the serialized output looks like in the event of `Map(key -> None)`? – Danny Dec 03 '16 at 23:17
  • I use JSON4S and from my experience `Option` types dont get serialized with any indication of being option, just as you described. The reason that's not an issue is because when I deserialize its smart enough to stick the values into `Option`s since I specify the type I'm deserializing into. You however have an interesting case that I have not encountered, that is a collection of `Option`s. I would suggest that perhaps you should rethink your design, if your key maps to a `None` then its really as if the KVP is not present at all, perhaps you should be using `Map[String, String]` – Danny Dec 03 '16 at 23:23

0 Answers0