I have the following method in my project

 public void execute(final int apiId, final ResponseHandler handler, final Type type)

and the type is determined using TypeToken as follows

final Type serviceErrorType = new TypeToken<>() {
    }.getType();

我在这里看过这个link,但对TypeTypeToken不能完全理解

任何人都可以分享一个链接或帮助理解这两个概念吗?

推荐答案

从您提供的link个选项中:

强制客户端创建此类的子类,这样即使在运行时也可以检索类型信息.

让我们举个例子.

Assume you want to parse a JSON to Java class with Gson library. Now, you have to specifically tell Gson, that:

I want this JSON to be translated to a List of User objects

How would you tell that to Gson? If it was only User, you could tell User.class. But it isn't possible to say List<User>.class

new Gson().fromJson(json, new TypeToken<List<User>>(){}.getType())

但现在您可以精确地指定Gson应该将其转换为List of Users.

应该引用文档中的解释:

表示泛型类型T.Java还没有提供表示泛型类型的方法,所以这个类提供了.

Have a look at this blog post for more details on the topic.

Json相关问答推荐

如何在Vega中使标记的符号在鼠标指针悬停时可点击

PowerShell女士:如何处理json对象?

JOLT转换以根据条件删除json对象

基于 JSON 字段的 Jolt 条件标志

使用 jq 从带有转义反斜杠字符的嵌套 JSON 中提取数据

在 python 中循环 JSON 数组

jq :遍历 json 并在键存在时检索集合

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

我无法在 Go - Gin 中解析日期/时间

无法向 Json 数组添加新元素

以 JSON 格式访问(新型、公共)Google 工作表

使用 c# 通用地展平 Json

以 unicode 将 pandas DataFrame 写入 JSON

错误未判断调用put(K, V)作为原始类型java.util.HashMap的成员

如何创建 JSON 对象 Node.js

关于使用 $ref 的 JSON 模式

在 Webpack 中加载静态 JSON 文件

如何从 MVC 控制器返回 Json 对象以查看

如果键可能不存在,则从 Python dict 读取

如何对 Javascript 对象进行排序,或将其转换为数组?