javaandroidgoogle-cloud-firestorejava-runtime-compiler

How to catch a "Could not deserialize object." exception in Java (Android)?


So let's say I'm converting a large collection of data from a server into custom local java objects. The POJO has an int variable, which is what I expect to get from the server. Only, let's say some of the data lists the number as a string instead of an integer. I have a for loop set up like:

for (Object document : DataSentFromServer) {                                   
   MyObjectClassArrayList.add(document.toObject(MyObject.class));
}

So for 99% of the documents have the int as an int, but one has it as a String. Thus when the for loop reaches that document it throws the java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to int I know that I need to update the data on the server, I already did this to solve the issue.

My question is: How can I create a catch block or something that will simply skip over documents from the server that don't match the data model of my object class? As I don't want my client side apps crashing if something is wrong with server data.


Solution

  • Simple surround the function with try catch block:

    for (Object document : DataSentFromServer) {  
        try{                                 
           MyObjectClassArrayList.add(document.toObject(MyObject.class));
        }catch(RuntimeException e){
          //do something with the bad data if you wish.
        }
    }