将 JSONArray 转换为 Iterable<JSONObject> - Kotlin
Casting JSONArray to Iterable<JSONObject> - Kotlin
我在 Kotlin 中使用 Json-Simple。
在什么情况下可以施法:
val jsonObjectIterable = jsonArray as Iterable<JSONObject>
变得危险? jsonArray
是一个 JSONArray
对象。
你可以施法成功,因为JSONArray is-A Iterable
. but it can't make sure each element in JSONArray is a JSONObject。
JSONArray is a raw typeList
表示可以加什么,例如:
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()
所以这就是为什么变得危险。另一方面,如果您只想将 JSONObjecs into the JSONArray, you can cast a 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"
以下是一个相当简单的实现。
假设你的对象是人
data class Person( val ID: Int, val name: String): Serializable
val gson = Gson()
val persons: Array<Person> = gson.fromJson(responseSTRING, Array<Person>::class.java)
现在 persons 是 Array of Person
我在 Kotlin 中使用 Json-Simple。
在什么情况下可以施法:
val jsonObjectIterable = jsonArray as Iterable<JSONObject>
变得危险? jsonArray
是一个 JSONArray
对象。
你可以施法成功,因为JSONArray is-A Iterable
. but it can't make sure each element in JSONArray is a JSONObject。
JSONArray is a raw typeList
表示可以加什么,例如:
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()
所以这就是为什么变得危险。另一方面,如果您只想将 JSONObjecs into the JSONArray, you can cast a 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"
以下是一个相当简单的实现。
假设你的对象是人
data class Person( val ID: Int, val name: String): Serializable
val gson = Gson()
val persons: Array<Person> = gson.fromJson(responseSTRING, Array<Person>::class.java)
现在 persons 是 Array of Person