score:-1

Accepted answer

My problem was a race condition due to not using chaining in my mapper configuration singleton.

My old code was more like this:

private var mapper: ObjectMapper with ScalaObjectMapper = _

def getMapper: ObjectMapper with ScalaObjectMapper = {
  if (mapper == null) {
    mapper = new ObjectMapper() with ScalaObjectMapper
    mapper.registerModule(DefaultScalaModule)
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
  }
  mapper
}

As you can see, if one thread initializes the mapper, but hasn't yet disabled unknown properties failure, a second thread could return and use a mapper that hasn't had that flag set yet, which explains why I was seeing the error only some of the time.

The correct code uses chaining so that the mapper singleton is set with all of the configuration:

private var mapper: ObjectMapper = _

 def getMapper: ObjectMapper = {
   if (mapper == null) {
     mapper = new ObjectMapper()
       .registerModule(DefaultScalaModule)
       .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
   }
   mapper
 }

(I also removed the experimental ScalaObjectMapper mix-in.)

score:-1

Try jsoniter-scala and you will enjoy how it can be handy, safely, and efficient to parse and serialize JSON these days with Scala: https://github.com/plokhotnyuk/jsoniter-scala

One of it's crucial features is an ability to generate codecs in compile time and even print their sources. You will have no any runtime magic like reflection or byte code replacement that will affect your code.

score:0

I made one simple test like this:

case class TestClass (counts: mutable.HashMap[String, Long])

And I converted it like:

val objectMapper = new ObjectMapper() with ScalaObjectMapper
objectMapper.registerModule(DefaultScalaModule)

val r3 = objectMapper.readValue("{\"counts\":{\"foo\":1,\"bar\":2}}", classOf[TestClass])

And apparently it works for me. Maybe it's something about the version you're using of Jackson, or Scala. Have you tried different versions of Jackson for example?


Related Query

More Query from same tag