[英]Adding JSONObject.KeySet() to a Mutable Set in scala
I am new to scala. 我是scala的新手。 I am working with some JSON objects and would like to get a set of all the keys available in the JSON Objects. 我正在使用一些JSON对象,并希望获得JSON对象中所有可用键的集合。 I am trying to do something like this: 我正在尝试做这样的事情:
var set = scala.collection.mutable.Set[String]()
for(condition) {
set ++= jsonObject.keySet().asInstanceOf[Set[String]]
}
when I run the code, I get the following error: 运行代码时,出现以下错误:
java.lang.ClassCastException: java.util.HashMap$KeySet cannot be cast to scala.collection.mutable.Set
The error speaks for itself. 错误说明了一切。 I also tried writing the keys to a file: 我还尝试将密钥写入文件:
json2.keySet().toArray().foreach { x => keysWriter.write(x) }
The IDE gives an error saying: overloaded method value write with alternatives: (x$1: Int)Unit <and> (x$1: String)Unit <and> (x$1: Array[Char])Unit cannot be applied to (Object)
IDE给出一个错误消息: overloaded method value write with alternatives: (x$1: Int)Unit <and> (x$1: String)Unit <and> (x$1: Array[Char])Unit cannot be applied to (Object)
So, what would be a better approach to get an accessible list of keys ? 那么,哪种更好的方法来获取可访问的键列表?
Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。
You could use JavaConverters
: 您可以使用JavaConverters
:
import scala.collection.JavaConverters._
val keys = jsonObject.keySet.asScala
keys
is a scala.collection.mutable.Set
. keys
是一个scala.collection.mutable.Set
。 To create an immutable Scala Set
, do this instead: 要创建一个不变的Scala Set
,请执行以下操作:
val keys = jsonObject.keySet.asScala.toSet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.