问题描述
我正在使用 Json-简单在科特林.
在什么情况下可以投放:
In what situations could this cast:
val jsonObjectIterable = jsonArray as Iterable<JSONObject>
变得危险了吗? jsonArray
是JSONArray
对象.
Become dangerous? jsonArray
is a JSONArray
object.
推荐答案
由于 JSONArray 是- Iterable
.但无法确保 JSONArray 是 JSONObject .
You can cast it successfully, since JSONArray is-A Iterable
. but it can't make sure each element in JSONArray is a JSONObject.
JSONArray 是原始类型 List
,这意味着它可以添加任何东西,例如:
The JSONArray is a raw type List
, which means it can adding anything, for example:
val jsonArray = JSONArray()
jsonArray.add("string")
jsonArray.add(JSONArray())
当代码从原始类型JSONArray
对向下转换的泛型类型Iterable<JSONObject>
进行操作时,可能会抛出ClassCastException
,例如:
When the code operates on a downcasted generic type Iterable<JSONObject>
from a raw type JSONArray
, it maybe be thrown a ClassCastException
, for example:
val jsonObjectIterable = jsonArray as Iterable<JSONObject>
// v--- throw ClassCastException, when try to cast a `String` to a `JSONObject`
val first = jsonObjectIterable.iterator().next()
所以这就是为什么变得危险的原因.另一方面,如果您只想添加 JSONObjec 放入 JSONArray ,可以强制转换原始类型 JSONArray 为通用类型MutableList<JSONObject>
,例如:
So this is why become dangerous. On the other hand, If you only want to add JSONObjecs into the JSONArray, you can cast a raw type JSONArray to a generic type MutableList<JSONObject>
, for example:
@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"
这篇关于将JSONArray转换为Iterable< JSONObject> -科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!