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

使用GSON反序列化通用类型

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

使用GSON反序列化通用类型

您必须

T
在反序列化时指定的类型。如果不知道要实例化什么,将如何创建您
List
的?它不会永远存在。因此,您将提供类型作为参数。
posts``Gson``Type``T``T``Class

现在假设,类型

posts
String
你会反序列化
MyJson<String>
的(我还添加了一个
Stringjson
用于简单的参数,你会从你读
reader
如前):

doInBackground(String.class, "{posts: ["article 1", "article 2"]}");protected MyJson<T> doInBackground(Class<T> type, String json, Void... params) {    GsonBuilder gson = new GsonBuilder();    Type collectionType = new TypeToken<MyJson<T>>(){}.getType();    MyJson<T> myJson = gson.create().fromJson(json, collectionType);    System.out.println(myJson.getPosts()); // ["article 1", "article 2"]    return myJson;}

同样,反序列

MyJson
Boolean
对象

doInBackground(Boolean.class, "{posts: [true, false]}");protected MyJson<T> doInBackground(Class<T> type, String json, Void... params) {    GsonBuilder gson = new GsonBuilder();    Type collectionType = new TypeToken<MyJson<T>>(){}.getType();    MyJson<T> myJson = gson.create().fromJson(json, collectionType);    System.out.println(myJson.getPosts()); // [true, false]    return myJson;}

我假设

MyJson<T>
我的例子是

public class MyJson<T> {    public List<T> posts;    public List<T> getPosts() {        return posts;    }}

因此,如果您要反序列化a

List<MyObject>
,则可以将该方法调用为

// assuming no Void parameters were requiredMyJson<MyObject> myJson = doInBackground(MyObject.class);


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

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

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