Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Scala Module, nested Lists and Maps

I wish to convert lists of json objects, which in themselves may contain Json objects, or Lists of Json objects and would like the results to be Scala Maps or Lists as appropriate, however, I can only get the top level object to convert to a Map or a List. Is there a simple way to do this?

For example in REPL

objectMapper.readValue("{\"test\":\"113123\",\"myList\":[{\"test2\":\"321323\"},{\"test3\":\"11122\"}]}", classOf[Map[String,Any]])

Will return

res: Map[String,Any] = Map(test -> 113123, myList -> [{test2=321323}, {test3=11122}])

Where I would like

res: Map[String,Any] = Map(test -> 113123, myList -> List(Map(test2 -> 321323), Map(test3 -> 111222)))
like image 772
J Pullar Avatar asked Feb 22 '26 13:02

J Pullar


1 Answers

OK so using a later version of the scala jackson module I created this class

private class NestedTypeObjectDeserializer extends JacksonUntypedObjectDeserializer {

  override def mapArray(jp: JsonParser, ctxt: DeserializationContext): AnyRef =
    super.mapArray(jp, ctxt).asInstanceOf[ArrayList[AnyRef]].asScala.toList

  override def mapObject(jp: JsonParser, ctxt: DeserializationContext): AnyRef =
    super.mapObject(jp, ctxt).asInstanceOf[LinkedHashMap[String, AnyRef]].asScala.toMap
}


private object NestedTypeObjectDeserializerResolver extends Deserializers.Base {

  lazy val OBJECT = classOf[AnyRef]

  override def findBeanDeserializer(javaType: JavaType,
                                    config: DeserializationConfig,
                                    beanDesc: BeanDescription) =
    if (!OBJECT.equals(javaType.getRawClass)) null
    else new NestedTypeObjectDeserializer
}

trait NestedTypeObjectDeserializerModule extends JacksonModule {
  this += (_ addDeserializers NestedTypeObjectDeserializerResolver)
}

which you can apply to the object mapper

val objectMapper = new ObjectMapper()
val module = new OptionModule with MapModule with SeqModule with IteratorModule with NestedTypeObjectDeserializerModule {}
objectMapper.registerModule(module)
like image 53
J Pullar Avatar answered Feb 25 '26 13:02

J Pullar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!