Casting JSONArray to Iterable<JSONObject> - Kotlin

試著忘記壹切 提交于 2019-12-23 22:56:55

问题


I am using Json-Simple in Kotlin.

In what situations could this cast:

val jsonObjectIterable = jsonArray as Iterable<JSONObject>

Become dangerous? jsonArray is a JSONArray object.


回答1:


You can cast it successfully, since JSONArray is-A Iterable. but it can't make sure each element in JSONArray is a JSONObject.

The JSONArray is a raw type List, which means it can adding anything, for example:

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

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()

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"



回答2:


Following is rather a simple implementation.

Suppose Your Object is Person

data class Person( val ID: Int, val name: String): Serializable
val gson = Gson()
val persons: Array<Person> = gson.fromJson(responseSTRING, Array<Person>::class.java)

Now persons is an Array of Person



来源:https://stackoverflow.com/questions/45281424/casting-jsonarray-to-iterablejsonobject-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!