我将这些类用kotlin,Location编写,其余的都在Application.kt
中@RealmClass
open class Location(
@PrimaryKey
@SerializedName("id")
var id: Int = 0,
@SerializedName("city_name")
var city_name: String? = null,
@SerializedName("elevation")
var elevation: Int = 0,
@SerializedName("state_code")
var state_code: String? = null,
@SerializedName("state_name")
var state_name: String? = null,
@SerializedName("country_code")
var country_code: String? = null,
@SerializedName("country_name")
var country_name: String? = null
):RealmObject()
其余的:
private fun loadStuff() {
val inputStream = this.resources.openRawResource(R.raw.city_json)
val jsonReader = JsonReader(InputStreamReader(inputStream, "UTF-8"))
val gson = Gson()
Realm.getDefaultInstance().executeTransactionAsync(Realm.Transaction { realm ->
val weatherList = gson.fromJson<List<Location>>(jsonReader , Array<Location>::class.java).toList()
//realm.insertOrUpdate(location)
jsonReader.endArray()
jsonReader.close()
}, Realm.Transaction.OnSuccess {
Log.d("TAG", "Success")
})
}
我一直异常:
com.example.android.sunshine.data.Location[] cannot be cast to java.lang.Iterable
我做错了什么?
对象看起来像这样:
[
{
"id":3040051,
"city_name":"les Escaldes",
"elevation":0,
"state_code":"08",
"state_name":"Parròquia d'Escaldes-Engordany",
"country_code":"AD",
"country_name":"Andorra"
},
{
"id":3041563,
"city_name":"Andorra la Vella",
"elevation":0,
"state_code":"07",
"state_name":"Parròquia d'Andorra la Vella",
"country_code":"AD",
"country_name":"Andorra"
}
]
答案 0 :(得分:0)
此:
List<Location>
是位置列表。 List实现了Iterable。
此:
Array<Location>
是一个位置数组。 Array没有实现Iterable。
差异大于此,但他是你的错误。
答案 1 :(得分:0)
将List与Array交换并移除.toList()就足够了,它就像魔术一样工作