To decode (deserialize) JSON data in Jetpack Compose seems quite simple, however I’ve encountered a problem that I can’t solve. I’m using the latest version of Android Studio and I’m not sure whether the .decodeFromString()
function works in AS or I should use IntelliJ IDEA for this? Here’s my code:
dependencies {
implementation(libs.kotlinx.serialization.json)
}
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@ExperimentalSerializationApi
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
JSONsibleTheme {
DecodedText()
}
}
}
}
@Serializable
data class User(val id: Int, val name: String)
@ExperimentalSerializationApi
@Composable
fun DecodedText() {
val jsonString = """
{
"id": 722549,
"name": "John Smith"
}
"""
val deserialized = Json.decodeFromString<User>(string = jsonString)
Text(
text = "${deserialized.name}, ${deserialized.id}"
)
}
I can’t run this code either on a simulator or a real device because the @Serializable
annotation doesn’t apply (it’s underlined in yellow). The Warning says:
// kotlinx.serialization compiler plugin is not
// applied to the module, so this annotation would
// not be processed. Make sure that you've setup
// your buildscript correctly and re-import project.
2
Answers
I would like to complement @AtickFaisal answer (anyway thank you, Atick, for pointing the right direction), because with all these settings specified (including compose compiler plugin), my Jetpack Compose app runs without errors and successfully decodes JSON data.
Project
build.gradle.kts
Module
build.gradle.kts
libs.versions.toml
Here is a screenshot.
You also need to apply the plugin to your
root
build.gradle.kts
fileand your
app
build.gradle.kts
file: