无法将String转换为数据类对象-Firebase实时数据库 [英] Can't convert String to data class objects - Firebase realtime database
问题描述
我也阅读了有关同一问题的其他评论,但没有人提到类似我的情况
I have read other comments on this same issue, but none of them has touched on a situation like mine
在我的文章中,下面介绍了数据的结构:
In mine, below describes how the data is structured:
{
"symbols":{
"alphabets":{
"a":{
"available":true,
"text":"A",
"timestamp":1.512686825309134E9
},
"b":{
"available":true,
"text":"B",
"timestamp":1.512687248764272E9
}"NameOfSymbols":"alphabets"
}
}
}
*我的显示错误的原因是它无法转换字符串"NameOfSymbols":对数据类中指定的对象使用字母"
*The reason why mine is showing the error is that it can't convert the string "NameOfSymbols" : "alphabets"
to the objects as specified in the data class
因此,我可以使用Kotlin
有没有一种方法可以排除那部分children值,而只获得数据类中指定的那一部分?
数据类
data class alphabets(
val name: Names,
var NameOfSymbols: String? = null) {
data class Names(
var available: Boolean? = null,
var text: String? = null,
var timestamp: Long? = null) {
}
}
推荐答案
此结构可能适用于您的情况(未经测试):
This structure might work for your case (untested):
data class Message(
@PropertyName("symbols") val symbols: Symbols,
)
data class Symbols(
@PropertyName("alphabets") val alphabets: Alphabets,
)
data class Alphabets(
@PropertyName("a") val a: Alphabet,
@PropertyName("b") val b: Alphabet,
@PropertyName("NameOfSymbols") val nameOfSymbols: String,
)
data class Alphabet(
@PropertyName("available") val available: Boolean,
@PropertyName("text") val text: String,
@PropertyName("timestamp") val timestamp: Long,
)
用法是:
// in your ValueEventListener
override fun onDataChange(snapshot: DataSnapshot) {
val value = snapshot.getValue<Message>()
}
如果要排除 NameOfSymbols
,则应将其删除,并添加 @IgnoreExtraProperties
,如下所示:
If you want to exclude your NameOfSymbols
, you should remove it, and add the @IgnoreExtraProperties
, like shown below:
@IgnoreExtraProperties
data class Alphabets(
@PropertyName("a") val a: Alphabet,
@PropertyName("b") val b: Alphabet,
)
注意,我使用了这些版本的Firebase数据库:
NOTE, I used these versions of firebase database:
implementation 'com.google.firebase:firebase-database:19.7.0'
implementation 'com.google.firebase:firebase-database-ktx:19.7.0'
这篇关于无法将String转换为数据类对象-Firebase实时数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!