[英]How to let json4s or other scala json libs generate Java Collections
Background: 背景:
Map[String, Any]
as the result type to json4s' extract method (viz. parse(json).extract[Map[String, Any]]
) 输入的JSON项目是动态的,因此我只能将Map[String, Any]
作为json4s提取方法的结果类型(即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
我从Java库得到一个异常,说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 (eg ["a", "b", "c"]
=> scala.collection.immutable.List("a", "b", "c")
) 我想这是因为Json4s只是产生阶List
但爪哇List
为JArray
元件(例如["a", "b", "c"]
=> scala.collection.immutable.List("a", "b", "c")
)
So, the question is how I can handle the case? 那么,问题是我该如何处理此案?
You should stick to the scala types for json4s (and in general for all scala code). 您应该坚持使用json4s的scala类型(通常是所有scala代码)。 Then you can use scala.collection.JavaConverters to convert the scala object in the following way. 然后,您可以使用scala.collection.JavaConverters通过以下方式转换scala对象。
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. 如果确实需要ArrayList(而不仅是java.util.List
),我将以以下方式创建它。
val arrayList = new ArrayList(javaList)
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]](){})
mapper = new com.fasterxml.jackson.databind.ObjectMapper
mapper.readValue(org.json4s.jackson.Serialization.write(scalaMap), new TypeReference[java.util.Map[String, Object]](){})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.