繁体   English   中英

如何从 Firestore 中的嵌套数组中读取数据

[英]How to read data from nested array in Firestore

我的 Firestore 中有以下结构,我想读取数据并将其存储在 ArrayList 中,就像我有“amountArrayList”,它将从 Firestore 中的“事务”字段读取数据,我想从“交易”字段并制作它的数组列表,以便我可以以列表方式显示它。 Firestore 结构图

我的代码

Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getKey().equals("transactions")) {
        System.out.println(entry.getValue().toString());
    }
}

Output

[{transactionType=Credit, amount=3000, dateToStr=17/12/2021, timeToStr=08:06:10, description=}, {transactionType=Credit, amount=2000, dateToStr=17/12/2021, timeToStr=08 :06:50,描述=}]

由于transactions是一个数组字段,因此您从entry.getValue()获得的值是一个对象List 由于 JSON 中的每个对象都具有属性,因此在 Java 代码中,它们每个都将再次成为Map<String, Object>

打印金额的简单方法如下:

List transactions = document.get("transactions");
for (Object transaction: transactions) {
  Map values = (Map)transaction;
  System.out.println(values.get("amount")
}

虽然 Frank van Puffelen 的回答可以很好地工作,但有一个解决方案,您可以直接将“事务”数组 map 放入自定义对象列表中。 假设您有一个如下所示的 class 声明:

class User {
    public String balance, email, firstname, lastname, password, username;
    public List<Transaction> transactions;

    public User(String balance, String email, String firstname, String lastname, String password, String username, List<Transaction> transactions) {
        this.balance = balance;
        this.email = email;
        this.firstname = firstname;
        this.lastname = lastname;
        this.password = password;
        this.username = username;
        this.transactions = transactions;
    }
}

一个看起来像这样的:

class Transaction {
    public String amount, dateToStr, description, timeToStr, transactionType;

    public Transaction(String amount, String dateToStr, String description, String timeToStr, String transactionType) {
        this.amount = amount;
        this.dateToStr = dateToStr;
        this.description = description;
        this.timeToStr = timeToStr;
        this.transactionType = transactionType;
    }
}

要获取列表,它将非常简单:

docRef.get().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        DocumentSnapshot document = task.getResult();
        if (document.exists()) {
            List<Transaction> transactions = document.toObject(User.class).transactions;
            List<String> amountArrayList = new ArrayList<>();
            for(Transaction transaction : transactions) {
                String amount = transaction.amount;
                amountArrayList.add(amount);
            }
            // Do what you need to do with your amountArrayList
        }
    }
});

您可以在以下文章中阅读更多信息:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM