Deserializing 2d array in kotlinx.serialization

Serialization/deserialization for arrays (including multi-dimensional) works out of the box. Unexpected behavior is related to init section of your data class. It’s executed after deserialization happens and overwrites data parsed from JSON.

It also happens when you create instance of Array2D manually:

val x = Array2D(1, 1, Array(1) { Array(1) { Thing("0") } })
println(x.arrayContents[0][0]) //will print null

You just need to replace init block with secondary constructor (default value for arrayContents is redundant, by the way), and you may declare arrayContents as val now:

data class Array2D(val width: Int, val height: Int, val arrayContents: Array<Array<Thing?>>) {
    constructor(width: Int, height: Int) : this(width, height, Array(width) { Array(height) { null } })

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top