将JSONArray转换为Iterable< JSONObject> -科特林 [英] Casting JSONArray to Iterable<JSONObject> - Kotlin

查看:447
本文介绍了将JSONArray转换为Iterable< JSONObject> -科特林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Json-简单在科特林.

在什么情况下可以投放:

In what situations could this cast:

val jsonObjectIterable = jsonArray as Iterable<JSONObject>

变得危险了吗? jsonArrayJSONArray对象.

Become dangerous? jsonArray is a JSONArray object.

推荐答案

由于 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 ,可以强制转换原始类型

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&lt; JSONObject&gt; -科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆