在Jetpack Compose中解码(反序列化)JSON数据似乎很简单,但我遇到了一个无法解决的问题。我使用的是最新版本的Android Studio,我不确定
.decodeFromString()
函数在AS中工作,还是我应该使用IntelliJ IDEA?这是我的代码:
dependencies {
implementation(libs.kotlinx.serialization.json)
}
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalSerializationApi::class)
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 = """
{
"user_id": 722549,
"name": "John Smith",
}
"""
val deserialized = Json.decodeFromString<User>(string = jsonString)
Text(
text = "${deserialized.name}, ${deserialized.id}"
)
}
我无法在模拟器或真实设备上运行此代码,因为
@Serializable
注释不适用(黄色下划线)。警告说:
// 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.