首先我要说的是,我对使用 Firebase 还很陌生。
我尝试使用 push() 将带有名为“mGameSessionID”的字符串的自定义对象推送到我的 Firebase 数据库:
DatabaseReference pushedPostRef =
myRef.child(myRef.push().getKey());
String gameSessionID = pushedPostRef.getKey();
GameSession gameSession = new GameSession(gameSessionID);
pushedPostRef.setValue(gameSession);
但是,当使用“.setValue(gameSession)”设置值时,它会向数据库添加一个额外的 gameSessionID 值
这是 GameSession 类:
String mGameSessionID;
GameSession()
{
}
GameSession(String gameSessionID)
{
mGameSessionID = gameSessionID;
}
public String getGameSessionID()
{
return mGameSessionID;
}
public void setGameSessionID(String gameSessionID)
{
mGameSessionID = gameSessionID;
}
最佳答案
Firebase 实时数据库 SDK 将使用反射来序列化对象实例上的所有可见字段和 JavaBean 类型 getter 方法以发现它们。因此,如果它看到一个字段“foo”,它将序列化一个名为“foo”的属性。如果它看到一个名为“getFoo”的 getter 方法,它将序列化一个也称为“foo”的属性。
对于像 GameSession 这样的 JavaBean 类型对象,带有访问器(getter 和 setter)的字段应该是私有(private)的,只允许通过它们进行访问:
private String mGameSessionID
这应该可以防止 SDK 看到 mGameSessionId
,而只使用可见的 getter 方法。
关于java - Android/Java Firebase 向键/引用添加意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47254769/