4

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.

2 Answers 2

4

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"
Sign up to request clarification or add additional context in comments.

2 Comments

I see. This jsonArray is the response of an API I trust (and is supposed to return a JSONArray of underlying JSONObjects). Therefore I could consider this as completely safe, right?
@pk1914 No. the json data type is not only have JSONObject&JSONArray , but also have string,boolean,number. and a JSONArray also can add any type of Object, e.g: add another json array add(JSONArray()).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.