[英]ArrayList<ArrayList<String>> in Parcelable object kotlin
需要对字符串数组的数组进行分块。 对象是这样的
data class Foo (
@SerializedName("bar") val bar: ArrayList<ArrayList<String>>,
)
它并不完全需要是 ArrayList。 也可以使用数组。
data class Foo (
@SerializedName("bar") val bar: Array<Array<String>>,
)
哪个更容易映射这个json数据
{
"bar": [
["a", "b"],
["a1", "b2", "c2"],
["a3", "b34", "c432"]
]
}
使用 kotlin 实验性Parcelize
在使用 progaurd 编译时会导致应用程序崩溃
它是如何在“writeToParcel”中写入并在“构造函数”中读取的?
data class Foo (
@SerializedName("bar") val bar: ArrayList<ArrayList<String>>,
) : Parcelable {
constructor(source: Parcel) : this(
// ?????
)
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
// ?????
}
}
您不能直接为List
of List
直接创建Parcelable
,因此一种解决方案是将所需List
一个子类设为Parcelable
并将其作为最终列表类型。 如何? 看看下面:
让我们首先创建我们的内部 String 类列表,如下所示:
class StringList() : ArrayList<String>(), Parcelable {
constructor(source: Parcel) : this() {
source.createStringArrayList()
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeStringList(this@StringList)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<StringList> = object : Parcelable.Creator<StringList> {
override fun createFromParcel(source: Parcel): StringList = StringList(source)
override fun newArray(size: Int): Array<StringList?> = arrayOfNulls(size)
}
}
}
我们在这里所做的是创建了我们的ArrayList<String>
可分块,以便我们可以在任何端点使用它。
所以最终的数据类将具有以下实现:
data class Foo(@SerializedName("bar") val bar: List<StringList>) : Parcelable {
constructor(source: Parcel) : this(
source.createTypedArrayList(StringList.CREATOR)
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeTypedList(bar)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<Foo> = object : Parcelable.Creator<Foo> {
override fun createFromParcel(source: Parcel): Foo = Foo(source)
override fun newArray(size: Int): Array<Foo?> = arrayOfNulls(size)
}
}
}
注意:这是基于OP的简单实现,您可以根据您的要求进行任何自定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.