我尝试了很多使用while循环将我的scala列表转换为Json;代码如下:
var json = null
while (list != null) {
json = new Gson().toJson(list)
}
该json
变量必须在循环之外访问,所以我在循环之外声明它并用 初始化null
,但是 Scala 编译器给了我一个类型不匹配异常......
Why are you using a while loop to convert a single list to JSON? Until you explain why you need a loop (or, repeated conversions to JSON, more generally speaking), I'd suggest the following trivial snippet:
val json = new Gson().toJson(list)
Note that I've also changed var json
to val json
.
However, if all you want to know is how to get rid of the type mismatch exception, just change:
var json = null
to
var json: String = null
or
var json: String = _
If you don't declare json
to be of type String
, Scala will implicitly take it to be (i.e. infer) of type Null
, and it's not possible to assign values of type String
to a variable of type Null
.
此函数适用于 List 和 Map 都使用普通的 Scala 构造:
def toJson(a: Any): String = {
a match {
// number
case m: Number => m.toString
// string
case m: String => "\"" + m + "\""
case m: Map[AnyRef, AnyRef] => {
"{" + (m map { x => val key = x._1; toJson(key) + ": " + toJson(m(key)) } mkString (", ")) + "}"
}
case l: Seq[AnyRef] => { "[" + (l map (toJson(_)) mkString (",")) + "]" }
// for anything else: tuple
case m: Product => toJson(m.productIterator.toList)
case m: AnyRef => "\"" + m.toString + "\""
}
}