How to fix nested arrays

98 views Asked by At

I have a data model class CategoryModel:

@Serializable
data class CategoryModel (val name: String, val items: ArrayList<String>) : java.io.Serializable {}

And I am trying to use Serialize so I can store the data from this class into a Bundle to be shared with another class:

    private fun displayCategoryItems(cat: CategoryModel) {

        val categoryItemsIntent = Intent(this, CategoryItemsActivity::class.java)
        val data: String = Json.encodeToString(cat)
        categoryItemsIntent.putExtra(categoryObjKey, data)

        startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }

I've noticed it has started doing wonky things with array brackets, and it looks like when i try to deserialize it, the items ArrayList is being converted to a string. So instead of

"items": "[1, 2]"

I get

"items":["[1, [2]]"]

What am I doing wrong?

1

There are 1 answers

2
Gustavo Bonaldi On BEST ANSWER

Just put the object that implements Serializable in the extras like:

    private fun displayCategoryItems(cat: CategoryModel) {

            val categoryItemsIntent = Intent(this, 
            CategoryItemsActivity::class.java)?.apply{
                   putExtra(categoryObjKey, data)
            }

           startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }

or pass like this:

    private fun displayCategoryItems(cat: Any) {
            val categoryItemsIntent = Intent(this, 
            CategoryItemsActivity::class.java)?.apply{
                   putExtra(categoryObjKey, cat as CategoryModel)
            }

           startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }