Cast from Object to List<String>: CastClassException

457 Views Asked by At

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?

4

There are 4 best solutions below

1
On BEST ANSWER

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.

0
On

You seems to be trying to cast the string array to a list of Strings leading to ClassCastException. Rather you should try put the elements of array in list using a loop.

0
On

The ClassCastException tells you the actual type of the object returned by document.get("categories"); so you can tell what you are able to cast it to.

0
On

From docs, ClassCastException means:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

Since, in your case, document.get returns general type Object and you try to cast it to List, you get this exception.