Home > Back-end >  kotlin serialization of array
kotlin serialization of array

Time:05-22

I am trying to serialise a fixed-size array of a data class into a JSON string, and then decode it back into an array, the problem is I can't seem to find the correct way to deserialize it into an array object

object LisStyles {

    @Serializable
    data class LisStyle(

        var priority: Int = 0,
        var backgroundColor: Int = Color.LTGRAY

    }
    
    var event = Array(MAX_ITEM_COUNT) { LisStyle() }
    
    fun serialiseData(){

        val output = Json.encodeToString(event)

        //The following line causes an exception
        event = Array(MAX_ITEM_COUNT) { Json.decodeFromString<LisStyle>(output) }

    }
}

A call to serialiseData() encodes the array correctly but gives a

JSON exception: Expected start of the object '{', but had 'EOF' instead

Can anyone suggest how to do this correctly?

Many thanks

CodePudding user response:

Try using event = Json.decodeFromString<Array<LisStyle>>(output) instead

  • Related