I'm having trouble deserializing a JSON object whi...
# serialization
v
I'm having trouble deserializing a JSON object which contains a base64 encoded string. Given the following class:
Copy code
@Serializable
class ImageDTO(val srcKey: String, val contentType: String, val bytes: String)
I get the following error:
Copy code
Could not deserialize body. Error is: Invalid symbol ':'(72) at index 4
The source JSON object looks like this:
Copy code
{"srcKey":"piCture.jpg","contentType":"image/jpeg","bytes":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD.......
So it looks like deserialization is being tripped up by the
"bytes":"data:image..."
part. Any suggestions? Perhaps I shouldn't be trying to upload images as a base64-encoded string?
a
What version of Kotlin/Kotlinx Serialization are you using? This works for me:
Copy code
import kotlinx.serialization.*
import kotlinx.serialization.json.*

fun main() {
  val data = """
    {"srcKey":"piCture.jpg","contentType":"image/jpeg","bytes":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD"}
  """.trimIndent()


  val i: ImageDTO = Json.decodeFromString(data)

  println(i)
}

@Serializable
data class ImageDTO(val srcKey: String, val contentType: String, val bytes: String)
Copy code
ImageDTO(srcKey=piCture.jpg, contentType=image/jpeg, bytes=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD)
v
Kotlin 1.9.20, serialization 1.9.0, serialization-json 1.5.0. I'll look for more information.
It's an IllegalArgumentException.
If a hand-code the base64 string, without
data:image/jpeg;base64,
then the deserialization actually works.
Bother. Works in unit tests, fails in production. The best kind of bug!
😥 1
I clearly need better error reporting; the error was not in deserialization, it was in the Base64 decode later on.
😞 1