Firestore document object (documentSnapshot) to POJO with nested maps

Viewed 340

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);
2 Answers

In this case, I don't think toObject() is going to work on the entire data structure. It's not meant for handling dynamic/variable data. Instead, you will have to manually:

  1. Iterate the entries of the Map of Maps that come back from the snapshot
  2. Convert each map to the individual objects
  3. Assemble the final MyPOJO object using what you found in the maps

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;

}
Related