因此,假设我要将服务器中的大量数据转换为自定义的本地Java对象。 POJO具有一个int变量,这是我希望从服务器获取的变量。仅,假设某些数据将数字列出为字符串而不是整数。我有一个for循环设置,例如:
for (Object document : DataSentFromServer) {
MyObjectClassArrayList.add(document.toObject(MyObject.class));
}
因此,对于99%的文档,其int均为int,但有人将其作为String。因此,当for循环到达该文档时,它将引发java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to int
,我知道我需要更新服务器上的数据,我已经这样做来解决问题。
我的问题是:我如何创建一个catch块或一些将跳过服务器中与我的对象类的数据模型不匹配的文档的文件?因为我不希望服务器数据出问题时客户端应用程序崩溃。
答案 0 :(得分:1)
用try catch块简单地包围函数:
for (Object document : DataSentFromServer) {
try{
MyObjectClassArrayList.add(document.toObject(MyObject.class));
}catch(RuntimeException e){
//do something with the bad data if you wish.
}
}
答案 1 :(得分:1)
@Marksim Novikov答案的一些更新。
for (Object document : DataSentFromServer) {
try{
MyObjectClassArrayList.add(document.toObject(MyObject.class));
}catch(RuntimeException e){
//continue will skip the current iteration and go to next iteration
continue;
}
}
因此,如果遇到Runtime异常,它将跳过该迭代并转到下一个迭代。