从Firebase Admin SDK导入json文件

时间:2019-05-31 21:06:41

标签: firebase firebase-realtime-database firebase-admin

我可以通过在Firebase控制台中导入json文件来更新整个数据库(真实数据库):

enter image description here

如何从服务器端(使用Firebase Admin)以编程方式进行操作?

我尝试过

private void uploadFirebaseDatabaseFile(JsonObject jsonObject) {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.setValue(jsonObject, (error, ref1) -> System.out.println(error + " " + ref1));
}

但是它会抛出java.lang.RuntimeException: java.lang.reflect.InvocationTargetException ... Caused by: java.lang.IllegalStateException: Not a JSON Primitive: { ...

1 个答案:

答案 0 :(得分:0)

解决了:

private void uploadFirebaseDatabaseFile(Gson gson, JsonObject jsonObject) throws Exception {
    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    CountDownLatch done = new CountDownLatch(1);
    // we must convert our JsonObject and its all nested children to Map<String, Object>
    ref.setValue(gson.fromJson(jsonObject, Map.class), (error, ref1) -> {
            System.out.println(error + " " + ref1);
        done.countDown();
    });
    done.await();
}