我有一个应用程序,可以在firebase实时数据库上写入数据库。我可以看到数据及其相关信息。
然后我只想读取数据,并自动将其编组到我的对象中。 JSON有几层:
{
"subjects" : {
"reports" : {
"A3VDf5q3gXefuFdK98OikTQYKEu2" : { <--multiple ones of these
"report" : {
"email" : "email@email.com",
"profile_image" : "<LINK REMOVED>",
"question_one" : {
"answer" : "NO",
"question" : "Blah blah?",
"reason" : "meh"
},
"question_two" : {
"answer" : "NO",
"question" : "Meh Meh?",
"reason" : "bleh"
},
"time_stamp" : "130719003955"
}
}
}
}
}
(为了简洁和隐私,我删除了一些值)
在我的代码中,我可以手动提取数据:
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser currentUser = mAuth.getCurrentUser();
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("subjects").child("reports").child(currentUser.getUid());
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "BEFORE CONVERSION::");
Log.d(TAG, "User UID::" + currentUser.getUid());
Log.d(TAG, "Children count::" + dataSnapshot.getChildrenCount());
Log.d(TAG, "Snapshot key::" + dataSnapshot.getKey());
Log.d(TAG, "Snapshot value::" + dataSnapshot.getValue());
Log.d(TAG, "Snapshot toString::" + dataSnapshot.toString());
Log.d(TAG, "email: " + dataSnapshot.child("report").child("email").getValue());
Log.d(TAG, "profile image: " + dataSnapshot.child("report").child("profile_image").getValue());
Log.d(TAG, "timeStamp: " + dataSnapshot.child("report").child("time_stamp").getValue());
Report report = dataSnapshot.child("report").getValue(Report.class);
Log.d(TAG, "Report: " + report.getProfileImage());
Log.d(TAG, "Report to string: " + report.toString());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Failed to get value from DB", databaseError.toException());
}
});
Report report = dataSnapshot.child("report").getValue(Report.class);
之后的所有内容均为空,出于某些原因,除了email
之外!!
显然,我想让它自动设置模型中的值:
public class Report {
@PropertyName("email")
private String email;
@PropertyName("profile_image")
private String profileImage;
@PropertyName("question_one")
private Question questionOne;
@PropertyName("question_two")
private Question questionTwo;
@PropertyName("time_stamp")
private String timeStamp;
public Report() {}
//Getters and setters
}
我还尝试过将监听器置于:
ref.child("report").addListenerForSingleValueEvent
但这是相同的结果。
我在做什么错了?
谢谢
答案 0 :(得分:1)
我相信您必须在Report
上的公共获取方法上使用@PropertyName注释,而不是私有字段名称。