【问题标题】:Cannot seem to understand Firebase's JSON table似乎无法理解 Firebase 的 JSON 表
【发布时间】:2016-05-20 17:32:05
【问题描述】:

假设我有这个 JSON 树:

"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName":"Jones"}
]

如何在Firebase 中执行此操作?每次我在“employees”下创建一个名为“firstname”的对象时,它都会用“Firstname”替换之前的对象。

我以前用过 Parse 的表格,但由于它已被删除,所以我需要帮助学习这个令人困惑的东西。

我使用的是安卓系统。

【问题讨论】:

  • 您可以在firebase.com/docs阅读官方文档。还请提及您要使用 Firebase 的平台(iOS、Android、Web),这样其他人会更容易帮助您。
  • @Dzikovskyy 我阅读了文档,但它并没有真正的帮助。
  • 插入我的平台也没用,但我会编辑帖子。
  • 你试过了吗employees.push({firstName:"newFirstName", lastName:"newLastName"})
  • @JoeHanink 我在哪里写的?也只是提醒我正在使用 Java。

标签: android json firebase firebase-realtime-database


【解决方案1】:

Firebase 数据库不支持列表或数组。如果我们尝试存储一个列表或一个数组,它实际上会被存储为一个以整数作为键名的“对象”(see doc)。

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

这样,您在 firebase 中的树将如下所示:

{"employees":{
        0:{"firstName":"John", "lastName":"Doe"}, 
        1:{"firstName":"Anna", "lastName":"Smith"}, 
        2:{"firstName":"Peter","lastName":"Jones"}
    }
}

使用 Firebase 术语,我们可以说节点 emloyees 具有三个 ID 分别为 0、1、2 的子节点。

但不建议在 Firebase 中使用整数 ID 保存数据 (see this to know why)。 Firebase 提供了一个 push() 函数,每次将新子项添加到指定的 Firebase 引用时,该函数都会生成一个唯一 ID。

这是 Firebase Android 文档中的一个示例:

//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");
    postRef.push().setValue(post1);

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

因此,在帖子节点中,我们将有两个具有自动生成 ID 的子节点:

{
  "posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    },
    "-JRHTHaKuITFIhnj02kE": {
      "author": "alanisawesome",
      "title": "The Turing Machine"
    }
  }
}

【讨论】:

    【解决方案2】:

    您可能正在寻找DatabaseReference.push(),它会在该位置下创建一个新子节点。

    var employeesRef = mDatabase.child("employees");
    var newEmployeeRef = employeesRef.push()
    newEmployeeRef.setValue(employee);
    

    了解更多信息的最佳位置是appending data to a list in the Firebase documentation 部分。

    【讨论】:

    • 我正在使用 Java。但我明白了。我看看有没有效果
    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2015-02-25
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多