Firebase for a custom Java object

{
  "users": {
    "mchen": {
      "friends": { "brinchen": true },
      "name": "Mary Chen",
      "widgets": { "one": true, "three": true }
    },
    "brinchen": { ... },
    "hmadi": { ... }
  }
}

How to write a custom object class for the above example? Guides in Firebase show just a simple example.

+4
source share
1 answer

As usual, you need a Java class that maps each property from JSON to the + getter field:

static class User {
    String name;
    Map<String, Boolean> friends;
    Map<String, Boolean> widgets;

    public User() { }

    public String getName() { return name; }
    public Map<String, Boolean> getFriends() { return friends; }
    public Map<String, Boolean> getWidgets() { return widgets; }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", friends=" + friends +
                ", widgets=" + widgets +
                '}';
    }
}

I just follow these instructions from the Firebase Android reading guide :

We will create a Java class that represents the blog post. Like last time, we need to make sure that the field names correspond to the property names in the Firebase database and give the class a constructor without parameters without parameters.

​​:

Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/34882779/users");
ref.addListenerForSingleValueEvent(new ValueEventListenerBase() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            System.out.println(userSnapshot.getKey()+": "+userSnapshot.getValue(User.class));
        }
    }
});

:

brinchen: User { name= 'Brin Chen', friends = {mchen = true, hmadi = true}, widgets = {one = true, three = true, two = true}}

hmadi: { name= 'Horace Madi', friends = {brinchen = true}, widgets = {one = true, two = true}}

mchen: User { name= 'Mary Chen', friends = {brinchen = true}, widgets = {one = true, three = true}}

+9

Source: https://habr.com/ru/post/1624997/


All Articles