将JSONArray投射到Iterable <JSONObject> – Kotlin

我在Kotlin中使用Json-Simple 。

在这种情况下,

val jsonObjectIterable = jsonArray as Iterable<JSONObject> 

变得危险? jsonArray是一个JSONArray对象。

因为JSONArray 是一个 Iterable ,所以你可以成功的投射它。 但它不能确保JSONArray中的每个元素都是JSONObject 。

JSONArray是一个原始类型的 List ,这意味着它可以添加任何东西,例如:

 val jsonArray = JSONArray() jsonArray.add("string") jsonArray.add(JSONArray()) 

当代码对原始类型为JSONArray通用类型Iterable<JSONObject>进行操作时,可能会引发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添加到JSONArray中 ,则可以将原始类型 JSONArray MutableList<JSONObject>转换为泛型类型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"