谷歌gson fromjson()TypeToken [英] google gson fromjson() TypeToken

查看:440
本文介绍了谷歌gson fromjson()TypeToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解Google的GSON api的fromJson方法的TypeToken.下面的代码对我来说很复杂...

I am not able to understand TypeToken of Google's GSON api's fromJson method. Below code is very complex to understand for me...

        Gson gson = new Gson();
        ArrayList<ID_Name_Address> al = new ArrayList<ID_Name_Address>();
        al = gson.fromJson(json, new TypeToken<List<ID_Name_Address>>(){}.getType());

这里到底发生了什么:new TypeToken<List<ID_Name_Address>>(){}.getType()

What exactly is happening here : new TypeToken<List<ID_Name_Address>>(){}.getType()

这是一个匿名班吗?对此代码进行一些说明.

is this a anonymous class? Throw some light on this code.

推荐答案

TypeToken是一种在运行时获取有关泛型信息的技巧,这要归功于具有完全指定的泛型超类的类可以通过反射获得该数据.

TypeToken is a trick to obtain information about generics at runtime thanks to the fact that classes with fully specified generic superclasses make that data available through reflection.

GSON用户指南在此处提供了有关序列化/反序列化泛型的部分: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types

The GSON user guide has a section on serializing/deserializing generics here: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types

要专门回答您的问题,它将创建一个匿名对象,该对象在其超类数据中捕获TypeToken的泛型.然后通过反射提取该数据,并与getType()打包为Type实例,以避免由于上述匿名类而导致的内存泄漏.

To specifically answer your question, it creates an anonymous object that captures the generics of TypeToken in its superclass data. That data is then extracted through reflection and packaged as a Type instance with getType() to avoid memory leaks due to the aforementioned anonymous class.

这篇关于谷歌gson fromjson()TypeToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆