【发布时间】:2015-04-27 08:01:04
【问题描述】:
我在服务器中序列化数据:
Gson gson = new Gson();
Map<String, List<?>> resultMap = BackendUpdateManager.getInstance()
.getUpdates(timeHolder, shopIdInt, buyerIdInt);
gson.toJson(resultMap);
并反序列化:
Gson gson = new Gson();
Map<String, List<?>> resultMap = gson.fromJson(json,
new TypeToken<Map<String, List<?>>>() {
}.getType());
但是,当我尝试使用 Map 中的项目时:
List<ProductCategory> productCategoryList = (List<ProductCategory>)updateMap.get(key);
for(ProductCategory productCategory : productCategoryList) {
}
我得到错误:
由:
java.lang.ClassCastException引起:com.google.gson.internal.LinkedTreeMap无法转换为com.example.model.entity.ProductCategory
如何修复此错误或使用List<different classes> 创建Map?
我尝试使用 getter 和 setter 创建类,其中包含不同类的 Lists 而不是 Map<String, List<?>>,并将其用于序列化和反序列化。但我正在寻找更好的方法。
【问题讨论】:
-
如果知道是
Map<String, List<ProductCategory>>,为什么还要反序列化为Map<String, List<?>>? -
@azurefrog 不仅是 List
。不同key不同类型: updateMap.get(key) -
作为错误点:当你反序列化时? GSON 和 JACKSON 使用某种映射来反序列化字符串,您需要自己进行映射。
-
@igreen 当我在反序列化后尝试使用 List> 中的对象时。当反序列化不正确时会发生此错误stackoverflow.com/questions/10356140/…