首页 > 解决方案 > 如何在嵌套对象中获取 Firestore GeoPoint 值?

问题描述

这是我从 Firestore DB 生成地理点数据类型的临时代码

firestoreDb.collection("products").document(productId).get()
  .addOnSuccessListener(documentSnapshot -> {
     Products products = documentSnapshot.toObject(Products.class); 
     countryCode = Objects.requireNonNull(products.getAddress().get("countryCode")).toString();

     String stringGeoPoint = products.getLocation().get("geoPoint").toString();
     System.out.println(stringGeoPoint);
     //Output: GeoPoint { latitude=29.339555, longitude=169.715858 }

     GeoPoint geoPoint = documentSnapshot.getGeoPoint(stringGeoPoint);// ?
     //Output: null
  }

Products.class

public class Products{ 
   public Map<String, Object> address;
   public Map<String, Object> location;

   public Map<String, Object> getAddress(){return address;}
   public Map<String, Object> getLocation(){return location;}
}

我的 Firestore 结构

在此处输入图像描述

标签: androidfirebasegoogle-cloud-firestore

解决方案


您发布了两个不同的代码,其中一个为您提供了正确的答案:

String stringGeoPoint = products.getLocation().get("geoPoint").toString();

这行代码显示 null :

GeoPoint geoPoint = documentSnapshot.getGeoPoint(stringGeoPoint);

原因 :

第一个代码背后的原因可以正常工作,因为当您检索数据时,您已经为文档字段创建了数据模型。你有你的方法getLocation(),它将返回 Location 数组。然后您通常可以通过传递 hashmap 的键来查看 hashmap 数组

位置是一个数组Hashmap<String, String>

所以第二个代码对你不起作用,因为 documentSnapshot 下没有字段。


推荐阅读