gpt4 book ai didi

Java 通过键名从对象中获取值

转载 作者:行者123 更新时间:2023-11-29 08:35:45 25 4
gpt4 key购买 nike

我从 Firebase 检索了一个对象,并想使用我想要其值的每个字段的名称来访问它的值。在 javascript 中,这就像 myObject.name 一样简单,用于检索对象中的名称。

我怎样才能用 Java 做同样的事情?

mDatabase = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
userId = user.getUid();

ValueEventListener myObjectListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "getting data");
Object myObject = dataSnapshot.getValue();

Log.v(TAG, myObject.toString());
// Outputs: {name= "john doe", hair="brown", isStudent=true, age=12}

// HERE is where I would like to get the name.
// DOES NOT work. Have also attempted things like
// myObject.getString("name"), etc.
myObject.getClass().getFieldName("name")
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};

mDatabase.child("users").child(userId).addValueEventListener(myObjectListener);

最佳答案

试试这个:

@SuppressWarnings("unchecked")
Map<String, Object> user = (Map<String, Object>) dataSnapshot.getValue();
String name = (String) user.get("name");
String hair = (String) user.get("hair");
long age = (Long) user.get("age");
...

如果您有一个 properly defined User 类,这会更好:

User user = dataSnapshot.getValue(User.class);
String name = user.getName();
String hair = user.getHair();
...

最后,还有第三种选择(使用 DataSnapshot.child(String) 方法):

String name = (String) dataSnapshot.child("name").getValue();
String hair = (String) dataSnapshot.child("hair").getValue();
...

关于Java 通过键名从对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44203090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com