[英]Iterator error for ArrayList: java.util.LinkedHashMap cannot be cast to MyObject
I have the following problem in Android: I store some data as an ArrayList in a Couchbase lite document: 我在Android中遇到以下问题:我将一些数据作为ArrayList存储在Couchbase lite文档中:
ArrayList<FluxDocReg> list_flux = (ArrayList<FluxDocReg>)doc.getProperty("flux");
if (list_flux == null)
list_flux = new ArrayList<FluxDocReg>();
FluxDocReg flux = new FluxDocReg();
//.....
list_flux.add(flux);
//save 'list_flux' in document
...
so until I have an ArrayList of LinkedHashedMap objects instead of FluxDocReg. 所以直到我有一个LinkedHashedMap对象的ArrayList而不是FluxDocReg。
Next, I read the property: 接下来,我阅读该属性:
if (documentBD != null && documentBD.getProperty("flux") != null)
{
ArrayList<FluxDocReg> list_flux = ArrayList<FluxDocReg>)documentBD.getProperty("flux");
///*****there are some objects in ArrayList, each of type LinkedHashedMap instead of FluxDocReg
for (int i = 0; i < list_flux.size(); i++)
{
****ERROR**** FluxDocReg flux = (FluxDocReg)list_flux.get(i);
}
}
I get an error when it tries to cast "FluxDocReg flux = (FluxDocReg)list_flux.get(i)" 尝试投射“ FluxDocReg流量=(FluxDocReg)list_flux.get(i)”时出现错误
I know that there are some objects in ArrayList, each of type LinkedHashedMap instead of FluxDocReg... 我知道ArrayList中有一些对象,每个对象的类型为LinkedHashedMap而不是FluxDocReg ...
What did I do wrong and how can I fix it? 我做错了什么,该如何解决?
Thanks, Catalin 谢谢,卡塔琳
Apparently there is something called "Java Type Erasure" for generics (lists of generics), so I had to come with a workaround. 显然,泛型(泛型列表)中有一种叫做“ Java类型擦除”的东西,所以我不得不提供一种解决方法。 Something like this, involving reflection and conversion to-and-from JSON:
像这样的事情,涉及到JSON的反射和转换:
List<FluxDocRegInfo> list_flux = null;
if (obj != null) {
//USING REFLECTION FOR AVOIDING TYPE ERASURE
Type listType = new TypeToken<ArrayList<FluxDocRegInfo>>() {}.getType();
list_flux = new Gson().fromJson(obj.toString(), listType);
}
else //flux is null
{
list_flux = new ArrayList<FluxDocRegInfo>();
}
///add something to the list
list_flux.add(flux);
JsonElement element = new Gson().toJsonTree(list_flux, new com.google.common.reflect.TypeToken<List<FluxDocRegInfo>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.