简体   繁体   English

反序列化地图 <String, List<?> &gt;使用Gson

[英]Deserialize Map<String, List<?>> using Gson

I serialize data in server: 我在服务器中序列化数据:

Gson gson = new Gson();
Map<String, List<?>> resultMap = BackendUpdateManager.getInstance()
    .getUpdates(timeHolder, shopIdInt, buyerIdInt);
gson.toJson(resultMap);

and deserialize: 和反序列化:

Gson gson = new Gson();
Map<String, List<?>> resultMap =  gson.fromJson(json,
    new TypeToken<Map<String, List<?>>>() {
    }.getType());

However, when I try use items from the Map : 但是,当我尝试使用Map项目时:

List<ProductCategory> productCategoryList = (List<ProductCategory>)updateMap.get(key);

for(ProductCategory productCategory : productCategoryList) {

}

I get error: 我收到错误:

Caused by: java.lang.ClassCastException : com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.model.entity.ProductCategory 引起: java.lang.ClassCastExceptioncom.google.gson.internal.LinkedTreeMap无法com.example.model.entity.ProductCategorycom.example.model.entity.ProductCategory

How can I fix this error or otherwise create a Map with List<different classes> ? 如何修复此错误或以其他方式创建带有List<different classes>Map

I've tried creating classes with getters and setters, that contains List s of different classes instead of Map<String, List<?>> and use it for serialization and deserialization. 我尝试使用getter和setter创建类,其中包含不同类的List而不是Map<String, List<?>>并将其用于序列化和反序列化。 But I'm looking for a better way. 但我正在寻找一种更好的方法。

How is Gson supposed to know that a particular Json string is a ProductCategory ? Gson如何知道特定的Json字符串是ProductCategory For instance, if the definition of ProductCategory is this: 例如,如果ProductCategory的定义是这样的:

package com.stackoverflow.vitvetal;  

public class ProductCategory {
    String name;
    String type;
}

And the Json is this: 而Json是这样的:

{
    "name":"bananas",
    "type":"go-go"
}

Where is the link that tells Gson to create an instance of a com.stackoverflow.vitvetal.ProductCategory ? 告诉Gson创建com.stackoverflow.vitvetal.ProductCategory实例的链接在哪里?

This link doesn't exist, because you didn't tell Gson about it. 此链接不存在,因为您没有告诉Gson。

So what gson does instead is, it creates a Map<String, String> that looks like 那么gson所做的是,它创建一个看起来像的Map<String, String>

"name" -> "bananas"
"type" -> "go-go"

If you want to do something different, the easiest thing to do - but also the least powerful - is to fully specify the parameterized type when you create your TypeToken ; 如果你想做一些不同的事情, 最简单的事情 - 也是最不强大的 - 是在你创建TypeToken时完全指定参数化类型; no wildcard <?> allowed. 没有通配符<?>允许。

If you need to do something more powerful, like creating maps with more variety in objects, you need to create a custom deserializer , using a TypeAdapter<T> , that teaches Gson how to handle your particular sort of object. 如果你需要做一些更强大的事情,比如在对象中创建更多种类的地图,你需要使用TypeAdapter<T>创建一个自定义反序列化器 ,它教会Gson如何处理你特定类型的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM