'Can we get data type of a field value from Firestore DB using Java?
I am fetching a JSON document from Firestore DB using java. I need to know the data type of the fields(values of json keys) in the JSON. Is there any way to know if a field value in Json is a String/Boolean/Number?
Solution 1:[1]
You could do it in a certain way. It's not exactly checking the type of a JSON field but getting the value's Object and checking its class. You will not interact with the JSON representing the document, but the document's snapshot.
To do so, you could use the get method to retrieve the value and read the object's class. For example:
ApiFuture<QuerySnapshot> query = db.collection("collection").get();
QuerySnapshot querySnapshot = query.get();
List<QueryDocumentsnapshot> documents = querySnapshot.getDocuments();
for (QueryDocumentSnapshot document : documents) {
Object field = document.get("field");
System.out.println("Document: " + document.getId());
System.out.println("Field: " + field + " (" + field.getClass() + ")");
System.out.println("----------");
}
Which would result in something like this:
Document: aaaaa
Field: hey (class java.lang.String)
----------
Document: bbbbb
Field: true (class java.lang.Boolean)
----------
Document: ccccc
Field: 99 (class java.lang.Long)
----------
As it can be seen, the field's class can be retrieved by retrieving the field as an Object and then checking its class. The get method exists precisely for the purpose of getting the value regardless of its type, but I'd still recommend using the specific methods (e.g. getString) whenever possible.
Solution 2:[2]
System.out.println(document.get("fieldname").getClass().getSimpleName());
prints something like:
field name : geo
field type : GeoPoint
field name : number
field type : Long
field name : field1
field type : String
field name : array
field type : ArrayList
field name : time
field type : Timestamp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajordat |
| Solution 2 | garawaa garawaa |
