javaandroidjsonektorptouchdb

Cast from Object to List<String>: CastClassException


I'm using a TouchDB with ektorp in an Android app to access a CouchDB

The json document I'm accessing has a array of categories:

categories: ['cat1', 'cat2']

In a view query i'm trying to access this array but I get a ClassCastException when trying to convert the result Object to a List:

 public void map(Map<String, Object> document, TDViewMapEmitBlock emitter) {
           Object dateAdded = document.get("dateAdded");
           Object expiryDate = document.get("expiryDate");
           boolean expired = false;
             if(expiryDate!=null){
                 expired = CompareDate.isItemExpired(expiryDate);
             }
           List<String> test = (List<String>)document.get("categories");

The .get() method works fine for single json fields. Any ideas?


Solution

  • document is declared as Map<String, Object>

    So when you do .get() - it will return an Object.

    There's no direct mapping to (List<String>) so this exception is saying you need to cast it to an object rather than a list.

    You could change the Map to hold a list of Strings in its values, this would then stop the class cast exception but you should probably review why the Map is declared in the way it is.