1

I try to store a data class using GSON as JSON string. However, gson always returns null:

fun jsonTest() {
    data class ImageEntry(
        val id: Int,
        val type: String,
        val path: String)

    val images = mutableListOf<ImageEntry>()
    images.add(ImageEntry(0, "test", "test"))
    Log.d("EXPORT_TEST", "$images")

    val gson = Gson()
    val jsonString = gson.toJson(images)
    Log.d("EXPORT_TEST", jsonString)
}

This returns

D/EXPORT_TEST: [ImageEntry(id=0, type=test, path=test)]
D/EXPORT_TEST: [null]

I tried using @SerializedName from here (Kotlin Data Class from Json using GSON) but same result.

gson 2.8.7 kotlin 1.5.10

What am I doing wrong?

GenError
  • 885
  • 9
  • 25

1 Answers1

3

I am not sure about the true "root" cause here, but this is happening because your ImageEntry class definition is local to the jsonTest() function. Move the class definition outside of the function:

data class ImageEntry(
    val id: Int,
    val type: String,
    val path: String
)

fun jsonTest() {
    val images = mutableListOf<ImageEntry>()
    images.add(ImageEntry(0, "test", "test"))
    Log.d("EXPORT_TEST", "$images")

    val gson = Gson()
    val jsonString = gson.toJson(images)
    Log.d("EXPORT_TEST", jsonString)
}

When I run this, the output appears as expected:

D/EXPORT_TEST: [{"id":0,"type":"test","path":"test"}]
Ben P.
  • 52,661
  • 6
  • 95
  • 123