Search code examples
androidserializationgoogle-cloud-firestorepojo

Firestore document object (documentSnapshot) to POJO with nested maps


My firestore document I'm trying to serialize contains a map of maps of strings like this:

Some example document in my collection:

id: "someId1" (String)
vouchers (Map)
    voucher_with_some_random_id_1 (Map)
        name: "name 1"
        description: "description 1"
    voucher_with_some_random_id_2 (Map)
        name: "name 2"
        description: "description 2"    

The problem I have with creating a matching POJO class is that the field names of the inner maps are not constant since the amount of vouchers in my vouchers Map changes from time to time.

For documents with unknown custom IDs there is a solution (Annotation @DocumentId)

But I couldn't find an annotation that works for maps.

My latest failed attempt:

public class MyPOJO {

    public MyPOJO() {
    }

    public String id;
    public VouchersPOJO vouchers;

}

public class VouchersPOJO {

    public VouchersPOJO() {
    }

    public List<ActualVoucherPOJO> vouchers;  

}

public class ActualVoucherPOJO {

    public ActualVoucherPOJO() {
    }

    public String name, description;

}

MyPOJO x = documentSnapshot.toObject(MyPOJO.class);

Solution

  • As you already say voucher is a Map, so that's what you should use in your Java class too:

    public class MyPOJO {
    
        public String id;
        public Map<String,Voucher> vouchers;
    
    }
    
    public class Voucher {
    
        public String name, description;
    
    }