0

Background:

  1. I use some Java libs which require Java Collections (java.util.ArrayList etc.)
  2. Input JSON items are dynamic, so I can only use Map[String, Any] as the result type to json4s' extract method (viz. parse(json).extract[Map[String, Any]])

Exception:

I got an exception from Java libs says java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to java.util.ArrayList

Reason:

I guess it is because Json4s just generates scala List but Java List for JArray elements (e.g. ["a", "b", "c"] => scala.collection.immutable.List("a", "b", "c"))

So, the question is how I can handle the case?

Tonny Tc
  • 852
  • 1
  • 12
  • 37

2 Answers2

0

You should stick to the scala types for json4s (and in general for all scala code). Then you can use scala.collection.JavaConverters to convert the scala object in the following way.

val list = List(1,2,3)
val javaList: java.util.List[Int] = list.asJava

yourJavaLib.call(javaList)

In case that you really need an ArrayList (and not only a java.util.List) I would just create it in the following way.

val arrayList = new ArrayList(javaList)
alexod
  • 111
  • 4
  • According to the background, I don't know `Map` values's type. So should I loop the whole `Map` and convert all the scala List to java list? – Tonny Tc Mar 29 '18 at 00:17
0

At the moment, I found an ugly but effective way for the case.

mapper = new com.fasterxml.jackson.databind.ObjectMapper mapper.readValue(org.json4s.jackson.Serialization.write(scalaMap), new TypeReference[java.util.Map[String, Object]](){})

Tonny Tc
  • 852
  • 1
  • 12
  • 37