我使用 Firestore(来自 Firebase)。由于我不明白我的一个类的变量没有以正确的名称保存(在 Firestore 中)的原因。
这是一个示例类:
data class ExampleClass(
val id: String,
val foo: String,
val bar: String,
val isEnabled: Bool)
当我在 Firestore 中保存此对象时,id
、foo
或 bar
没有任何问题。但是,isEnabled
保存为enabled
。 is
被删除,据我所知没有任何原因。
你们知道这是否正常吗?我想将该值保存为 isEnabled
而不是 enabled
。
此外,是否可以为每个值指定在 Firestore 中使用的“名称”?所以我可以强制将该值保存为“isEnabled”。我见过 @PropertyName ( Firebase doc ) 但它似乎没有达到我预期的效果。
提前致谢
最佳答案
这是正常且直观的。这是 JavaBean 类型对象序列化的方式。根据JavaBeans specification第 8.3.2 节 bool 属性忽略 bool getters 方法名称上的“is”:
Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is();
This "isPropertyName" method may be provided instead of a "get" method, or it may be provided in addition to a "get" method. In either case, if the is method is present for a boolean property then we will use the "is" method to read the property value. An example boolean property might be:
public boolean isMarsupial();
public void setMarsupial(boolean m);
在我看来,在 bool 值上添加“is”前缀有点多余。如果您知道某个属性是 bool 值,则意味着它隐式"is"或“不是”其名称中的内容。
但如果您确实必须更改名称,则可以使用 @PropertyName注释:
data class ExampleClass(
val id: String,
val foo: String,
val bar: String,
@PropertyName(value="isEnabled")
val isEnabled: Bool
)
关于Firebase Firestore : Is there an equivalent of @SerializedName?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925881/