AbAppletic AbAppletic - 1 year ago 92
JSON Question

Cannot seem to understand Firebase's JSON table

Let's say I have this JSON tree:

{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},

How can I do this in Firebase? Every time I create an object under "employees", with the name "firstname", it replaces the previous object with "Firstname".

I previously used Parse's tables, but since it's been taken down, then I need help learning this confusing thing.

I'm using Android.

Answer Source

Firebase databases have no native support for lists or arrays. If we try to store an list or an array, it really gets stored as an "object" with integers as the key names (see doc).

// we send this
['hello', 'world']
// Firebase databases store this
{0: 'hello', 1: 'world'}

In this way your tree in firebase would look like this:

        0:{"firstName":"John", "lastName":"Doe"}, 
        1:{"firstName":"Anna", "lastName":"Smith"}, 

Using Firebase terminology we can say that node emloyees has three child nodes with IDs 0,1,2 respectively.

But saving data with integer IDs in Firebase is not recommended (see this to know why). Firebase provides a push() function that generates a unique ID every time a new child is added to the specified Firebase reference.

Here is an example from Firebase Android doc.:

//create firebase ref using your firebase url    
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/android/saving-data/fireblog");

    Firebase postRef = ref.child("posts");

    Map<String, String> post1 = new HashMap<String, String>();
    post1.put("author", "gracehop");
    post1.put("title", "Announcing COBOL, a New Programming Language");

    Map<String, String> post2 = new HashMap<String, String>();
    post2.put("author", "alanisawesome");
    post2.put("title", "The Turing Machine");

And as a result in posts node we will have two childs with autogenerated ids:

  "posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    "-JRHTHaKuITFIhnj02kE": {
      "author": "alanisawesome",
      "title": "The Turing Machine"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download