Java按键名从对象获取值

时间:2017-05-26 13:38:53

标签: java json object firebase firebase-realtime-database

我从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);

3 个答案:

答案 0 :(得分:3)

试试这个:

@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();
...

答案 1 :(得分:0)

它适合我 Mehul。

String email = (String) ((LinkedHashMap) responseEntity.getBody().getPayload()).get("emailAddress");

答案 2 :(得分:-1)

比方说,您获得对象“ o”,并且想要获得字段名称“ userName”的值。

(String) ((LinkedHashMap) o).get("userName")