Search code examples
androidrealmretrofitretrofit2

Store key-less JSON to Realm using Retrofit


I want to save the following JSON from an online API directly to Realm using Retrofit. I am struggling to define the model because there are no keys and the values are dynamic.

JSON:

{
  "Plants": {
    "Green": [
      "Ascia",
      "Musca Arabica"
      ...
    ],
    "Yellow": [
      "Campona",
      "Zirata",
      ...
    ],
    ...
  }
}

Is this even doable? I know I can use a Map<String, Map<String, Set<String>>>, but makeing the Realm model is causing me trouble.


Solution

  • You could flatten it completely.

    public class Data extends RealmObject {
        @PrimaryKey 
        private String typeCategoryName; // "Plants_Green_Ascia"
    
        @Index
        private String type; // "Plants"
        @Index
        private String category; // "Green"
    
        private String name; // "Ascia"
    }
    

    Then you could query it like

    RealmResults<Data> data = realm.where(Data.class)
                                .equalTo("type", "Plants")
                                .equalTo("category", "Green")
                                .findAll();