栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用gson反序列化泛型

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用gson反序列化泛型

由于Java的类型擦除,Gson在集合方面有一些限制。您可以在此处了解更多信息。

从您的问题中,我看到您同时使用

ArrayList
linkedList
。您确定不是要只使用
List
接口吗?

此代码有效:

List<String> listOfStrings = new ArrayList<String>();listOfStrings.add("one");listOfStrings.add("two");Gson gson = new Gson();String json = gson.toJson(listOfStrings);System.out.println(json);Type type = new TypeToken<Collection<String>>(){}.getType();List<String> fromJson = gson.fromJson(json, type);System.out.println(fromJson);

更新 :我将您的课程更改为此,因此我不必弄乱其他课程:

class IndicesAndWeightsParams {    public List<Integer> indicesParams;    public List<String> weightsParams;    public IndicesAndWeightsParams() {        indicesParams = new ArrayList<Integer>();        weightsParams = new ArrayList<String>();    }    public IndicesAndWeightsParams(ArrayList<Integer> indicesParams, ArrayList<String> weightsParams) {        this.indicesParams = indicesParams;        this.weightsParams = weightsParams;    }}

使用此代码,一切对我有用:

ArrayList<Integer> indices = new ArrayList<Integer>();ArrayList<String> weights = new ArrayList<String>();indices.add(2);indices.add(5);weights.add("fifty");weights.add("twenty");IndicesAndWeightsParams iaw = new IndicesAndWeightsParams(indices, weights);Gson gson = new Gson();String string = gson.toJson(iaw);System.out.println(string);IndicesAndWeightsParams fromJson = gson.fromJson(string, IndicesAndWeightsParams.class);System.out.println(fromJson.indicesParams);System.out.println(fromJson.weightsParams);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485459.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号