Firebase To Custom Java Object
{ 'users': { 'mchen': { 'friends': { 'brinchen': true }, 'name': 'Mary Chen', 'widgets': { 'one': true, 'three': true } }, 'brinchen': { ... },
Solution 1:
As usual, you need a Java class that maps each property from the JSON to a field+getter:
staticclassUser {
String name;
Map<String, Boolean> friends;
Map<String, Boolean> widgets;
publicUser() { }
publicStringgetName() { return name; }
publicMap<String, Boolean> getFriends() { return friends; }
publicMap<String, Boolean> getWidgets() { return widgets; }
@OverridepublicStringtoString() {
return"User{" +
"name='" + name + '\'' +
", friends=" + friends +
", widgets=" + widgets +
'}';
}
}
I really just follow these instructions from the Firebase guide on reading data on Android:
We'll create a Java class that represents a Blog Post. Like last time, we have to make sure that our field names match the names of the properties in the Firebase database and give the class a default, parameterless constructor.
Then you can load the information like this:
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/34882779/users");
ref.addListenerForSingleValueEvent(new ValueEventListenerBase() {
@Override
publicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey()+": "+userSnapshot.getValue(User.class));
}
}
});
With this output:
brinchen: User{name='Brin Chen', friends={mchen=true, hmadi=true}, widgets={one=true, three=true, two=true}}
hmadi: User{name='Horace Madi', friends={brinchen=true}, widgets={one=true, two=true}}
mchen: User{name='Mary Chen', friends={brinchen=true}, widgets={one=true, three=true}}
Post a Comment for "Firebase To Custom Java Object"