我正在使用 Json-Simple在 Kotlin 。
在什么情况下可以转换:
val jsonObjectIterable = jsonArray as Iterable<JSONObject>
变得危险?
jsonArray
是 JSONArray
目的。
最佳答案
您可以成功施放它,因为 JSONArray is-A Iterable
.但它不能确定 JSONArray 中的每个元素是 JSONObject .
JSONArray是 raw type List
,这意味着它可以添加任何内容,例如:
val jsonArray = JSONArray()
jsonArray.add("string")
jsonArray.add(JSONArray())
当代码对向下转换的泛型类型进行操作时
Iterable<JSONObject>
来自原始类型 JSONArray
,它可能会被抛出 ClassCastException
, 例如:val jsonObjectIterable = jsonArray as Iterable<JSONObject>
// v--- throw ClassCastException, when try to cast a `String` to a `JSONObject`
val first = jsonObjectIterable.iterator().next()
所以这就是为什么变得危险。另一方面,如果您只想添加 JSONObjec s进入JSONArray ,你可以投一个 raw type JSONArray到泛型
MutableList<JSONObject>
, 例如:@Suppress("UNCHECKED_CAST")
val jsonArray = JSONArray() as MutableList<JSONObject>
// v--- the jsonArray only can add a JSONObject now
jsonArray.add(JSONObject(mapOf("foo" to "bar")))
// v--- there is no need down-casting here, since it is a Iterable<JSONObject>
val jsonObjectIterable:Iterable<JSONObject> = jsonArray
val first = jsonObjectIterable.iterator().next()
println(first["foo"])
// ^--- return "bar"
关于json - 将 JSONArray 转换为 Iterable<JSONObject> - Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281424/